Reputation: 27749
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
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
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
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
Reputation: 146310
go like this to loop
:
$('input, textArea').each(function(){
if($.trim($(this).val()) == ''){
console.log(this,'is empty');
}
});
Upvotes: 4