简体   繁体   中英

Make highlighted input field 'unhighlighted' when user starts typing

I made a simple form with javascript that highlights red fields if you click the "join" button and you leave a field blank.

Even after you fill it, until the "Join" button is pressed, it will continue to stay red. So instead of on click, I just want the highlight to be taken off once the user begins typing.

JSFiddle: http://jsfiddle.net/LCBradley3k/xqcJS/6/ Javascript:

$(document).ready(function(){


      /*  setTimeout(function(){ 
        $('.inputs').show("slide", { direction: "down" }, 1000);
        }, 2000);
    });*/

    $('#join').click(function(){

        var correct = true;

        $('input[type="text"]').each(function(indx){
            var $currentField = $(this);
            if ($currentField.val() === ''){
                $currentField.addClass('empty');
                correct = false;
            } else{
                $currentField.removeClass('empty');
            }

        });
        if (correct) {
            $('#answer').html('Thank You!');
            setTimeout(function(){
        $('.inputs').hide("slide", { direction: "up" }, 1000);
        }, 2000);
        } else {
        $('#answer').html('Please fill highlighted fields.') ;     
        }



    });

Add a keyup handler on the form inputs to remove the class:

$('input[type="text"]').keyup(function (event) {
    var $currentField = $(this);
    if ($currentField.val() !== '') {
        $currentField.removeClass('empty');
    }
});

DEMO

Sure, just bind to keydown.

http://jsfiddle.net/xqcJS/7/

if ($currentField.val() === ''){
    $currentField.addClass('empty');
    correct = false;
    $currentField.one('keydown',function(){
        $currentField.removeClass('empty');
    });
$('input[type="text"]').keydown(function() {
    if ( $(this).val != "" )
        $(this).removeClass('empty');
});

you can either use focus or use keyup.

$('input[type="text"]').keyup(function(e){
  $(this).removeClass('empty');
})

You can replace keyup with focus if you want to use the focus since it won't trigger the event each time you type.

Add the following piece of code:

$('input[type="text"]').focus(function() {            
   $(this).removeClass('empty');
});

The class 'empty' will be removed when you focus in on field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM