user3502199
user3502199

Reputation: 3

How can I use jQuery to check all inputs for blanks?

I am trying to use JQuery to check whether all inputs in a form have been filled. The viewer clicks a button and if the inputs have been filled, cool stuff happens. But if one of the fields hasn't been filled the viewer needs to get a custom warning message. I think I've almost got it but I need some help.

$(function() {
$("#btn_click").click(function() {
    if( $("input").val() == 0 ) {
    $("form").append('<span class=".warning">You didn\'t fill out all the fields!</span>');
}
    else {
        //Some cool stuff happens
    }
});

});

When I don't fill in any of the inputs, I get the expected behavior with the warning. That's good. However, the "cool stuff" runs if I fill in the first input and leave all the others blank. That's bad. I want the warning to show if any of the inputs are left blank. How can I make JQuery test all of the inputs?

Upvotes: 0

Views: 1715

Answers (5)

chandu
chandu

Reputation: 2276

$(function() {
$("#btn_click").on('click',function(e) {
    e.preventDefault();
    $("input").each(function(){
        if(!$(this).val()){
           //error message
            return false;
        }else{
           //remaining code
       }
    });
  });
});  

Upvotes: 2

A. Wolff
A. Wolff

Reputation: 74420

You could check it using:

if ($("input").length != $('input').filter(function () {
        return $.trim(this.value)
    }).length) {
    /* not all inputs filled */
}

Upvotes: 0

Valerij
Valerij

Reputation: 27758

try $("input").filter(function(){return this.value==''}).length > 0

or bettter, as you already are using jQuery use some sophisticated validation plugin

Upvotes: 0

Holt
Holt

Reputation: 37661

$('input').val() will only retrieve the value of the first input. If you want to check all the input, you should check all input with each (just an example, you can use others stuff) :

$('btn_click').on('click', function (e) {
    e.preventDefault(e) ;
    var allOk = true ;
    $('input').each(function () { // Iterate over input
        if (!$('input').val()) { // Don't check against 0
            allOk = false ; // If the input isn't ok
        }
    }) ;
    if (!allOk) {
        // Warning message
    }
    else {
        // Some cool stuff
    }
}) ;

Upvotes: 0

ashishmaurya
ashishmaurya

Reputation: 1196

You can add ID to each input element and then Using Jquery check if any one is blank then show error message otherwise do your cool stuff

Upvotes: 1

Related Questions