H3ll1n
H3ll1n

Reputation: 103

jquery - Check specific inputs for empty value and add class to ONLY those inputs that are empty

I have form that has input fields that are required, I point this out with made up class name. I have piece of code that kind of works. If I focus on required input and then press submit, that input will become red, if empty (which I want). But it only works only on one at a time and if I have focus on the input.

My code is as follows:

function checkIfEmpty(){
    $('#register-form input.gv-form-required').blur(function(){
        if( !$(this).val()){
            $(this).parent().parent().addClass("has-error");
            return false;
        }else{
            return true;
        }
    });
}

I am almost certain that the blur() method is not suitable for my situation. So help a man out here, please.

Upvotes: 2

Views: 4533

Answers (4)

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

Try this : You have to use .each() to check every input inside form and put removeClass in else condition.

function checkIfEmpty(){
    var empty = false;
    $('#register-form input.gv-form-required').each(function(){
        if($(this).val().trim()==""){
            empty = true;
            $(this).parent().parent().addClass("has-error");
        }else{
            $(this).parent().parent().removeClass("has-error");
        }
    });
    return empty;
}

Upvotes: 2

Balachandran
Balachandran

Reputation: 9637

try in else condition

$(this).parent().parent().removeClass("has-error");

js code

      if( !$(this).val()){
            $(this).parent().parent().addClass("has-error");

        }else{
            $(this).parent().parent().removeClass("has-error");

        }

Upvotes: 0

leopik
leopik

Reputation: 2351

The blur event indeed doesn't seem right in your situation. What I would do is that I would itterate through each field and checked whether it is filled or not. If it is, remove (if any) has-error class. If it isn't filled, give it the has-error class

function checkIfEmpty(){
    $('#register-form input.gv-form-required').each(function(){
        if($(this).val() === ""){
            $(this).parent().parent().addClass("has-error");
        }else{
            $(this).parent().parent().removeClass("has-error");
        }
    });
}

Upvotes: 1

Eiiki
Eiiki

Reputation: 320

change your code to the following:

function checkIfEmpty(){
   $('#register-form input.gv-form-required').each(function(){
       if( !$(this).is(':empty')){
           $(this).parent().parent().addClass("has-error");
       }else{
           $(this).parent().parent().removeClass("has-error");
       }
   });
}

Upvotes: 0

Related Questions