Detecting if at least one input (as array) is filled in jQuery
I've a group of inputs like <in开发者_运维百科put type="text" name="clients[]" />
that are loaded via AJAX. Before the user submits the form, I need to check if at least one of them has been filled. I don't know how to do this if is an array.
Thank you in advance!
Bind a function to the submit event for the form like this:
// assuming #foo is the form and each grouped element has classname bar
// also, this assumes that your form is not loaded by AJAX, but only the elements
// contained in it
$('#foo').submit(function() {
var elements = $("input[name='clients[]']");
var validated = false;
elements.each(function() {
if ($(this).val() != '') {
validated = true;
return false; // will break the each
} else {
validated = false;
}
});
return validated;
});
Live example here.
Like this:
var $filledTextboxes = $(":text[name='clients[]']").filter(function(){
return $.trim($(this).val()) != "";
});
if($filledTextboxes.size() == 0)
alert("All are empty");
else
alert("Not all are empty");
Hope this helps. Cheers
精彩评论