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

4

go like this to loop:

$('input, textArea').each(function(){
    if($.trim($(this).val()) == ''){
        console.log(this,'is empty');
    }
});
Sign up to request clarification or add additional context in comments.

Comments

4

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 Comments

+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.
Sorry about that. Missed the "return". Thanks.
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

Comments

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.