1

Using jQuery how can check if all input fields (EXCL hidden fields) and textareas are blank? I'm not sure how to "loop" through all form fields and check for:

$("input").val() and $("textarea).val()

This is to run a function that should only "work" if all form fields are blank.

4 Answers 4

5

Take your pick, but here it is in just a few lines to validate all the fields, not just one:

var allBlank = true;
$('input, textarea').each(function() {
    return allBlank = allBlank && !$(this).val();
}); 

Naturally you can modify the selector to specify just the fields you want. Then go on to:

if(allBlank) {
    //all are blank.  congrats. 
}

EDIT: Now with more performance!

2
  • 1
    +1 for the only answer here that is using boolean "flag", but it can be improved by breaking out of the loop when element with value is found - no point in iterating more elements. Commented Apr 8, 2011 at 19:16
  • Sorry about that. Missed the "return". Thanks. Commented Apr 8, 2011 at 19:23
4

go like this to loop:

$('input, textArea').each(function(){
    if($.trim($(this).val()) == ''){
        console.log(this,'is empty');
    }
});
1

I'd say extend jQuery to use the :blank pseudo class

taking an excerpt from the popular jquery.validate.js:

(function($) {
    $.extend($.expr[":"], {
        // http://docs.jquery.com/Plugins/Validation/blank
        blank: function(a) {
            return !$.trim(a.value);
        },
    });
})(jQuery);

then you can use a selector like

$("input:blank")

if you're doing more than just checking blanks you may consider using the jQuery validation plugin

bassistance.de » jQuery plugin: Validation

0

There are lots of ways to achieve that.

$('#form-id input').blur(function()
{
if( !$(this).val() ) {
      // Do whatever you need to do
}
});

$("input, textarea").each(function() {
if($(this).val() === "")
  alert("Empty Fields!!");
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.