Reputation: 34719
Using jQuery validation, if I have many fields on a page, and only require ONE of them to be filled, how do I raise an error only if they are all blank.
That is, the user can fill one or more fields, but if all of them are blank, there will be an error. I want to know if there is a way of doing this with jQuery validation.
Upvotes: 0
Views: 3502
Reputation: 77786
Something along these lines should work.
var valid=0;
$("#myform input[type=text]").each(function(){
if($(this).val() != "") valid+=1;
});
if(valid){
console.log(valid + " inputs have been filled");
}
else {
console.log("error: you must fill in at least one field");
}
See a working example here on jsFiddle
Upvotes: 6
Reputation: 9646
try this ,
var name = $('#name').val();
var city = $('#city').val();
if(name == '' && city == '') // this will only fire when both name and city are empty if one of them is not empty than this if condition will not fire
{
alert('all fields are required');
}
Upvotes: 0
Reputation: 342665
var filled = $("#theForm :input").filter(function() {
return $.trim(this.value).length;
});
if(filled.length) {
// at least one has been filled
} else {
// error, all are blank
}
Reference:
Upvotes: 2