Reputation:
Is there a shorter way of writing this for jQuery? Bundling it somehow? Seems awfully inefficient.
if (
($('#fname-field').val() == '') ||
($('#lname-field').val() == '') ||
($('#cell-field').val() == '') ||
($('#email-field').val() == '') ||
($('#street-field').val() == '') ||
($('#pcode-field').val() == '') ||
($('#city-field').val() == '') ||
) { // Do something }
I have searched around but haven't found an answer yet. I don't think the following is equivalent:
if ($('#fname-field, #lname-field, #cell-field etc...' == '')) { // Do something }
It's not equivalent since it doesn't run the conditions as a group, instead individually? Right?
Upvotes: 2
Views: 599
Reputation: 11382
You could give all the elements that you want to validate a class and then use jQuery's each function
$('.validate').each(function(index) {
if ($(this).val() == '')
alert("empty");
});
Or if you just want an alert once do:
$('.validate').each(function(index) {
if ($(this).val() == ''){
alert("empty");
return false;
}
});
Upvotes: 2
Reputation: 55750
You can try this approach
var isCheck = false;
var elems = $('#fname-field ,#lname-field , #cell-field , #email-field ,#street-field ,#pcode-field , #city-field' );
$.each(elems , function() {
if($this).val() == ''){
isCheck = true;
return false
}
});
if(isCheck){
// Your code here
}
else{
// Do something else
}
Upvotes: 0
Reputation: 383
var i = 0;
$('input').each(function() {
if($(this).val().length == '0') {
i++;;
}
});
alert("Found " + i + " empty fields");
Upvotes: 0
Reputation: 79830
You can do this..
if ($('#fname-field, #lname-field, #cell-field/*, ..*/')
.filter(function () {
return $(this).val();
}).length)
Upvotes: 0