stef
stef

Reputation: 27749

jQuery detect input fields are blank

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.

Upvotes: 1

Views: 7088

Answers (4)

Adam Terlson
Adam Terlson

Reputation: 12730

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!

Upvotes: 5

MikeM
MikeM

Reputation: 27405

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

Upvotes: 1

Piyush Mattoo
Piyush Mattoo

Reputation: 16115

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!!");
});

Upvotes: 0

Naftali
Naftali

Reputation: 146310

go like this to loop:

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

Upvotes: 4

Related Questions