Reputation: 687
I want to ask if there's a better way in jQuery to select multiple text input then check if any of them has a value. Here's my code:
if ($("#reference").val() != "" || $("#pin").val() != "" || $("#fName").val() != "" || $("#mName").val() != "" || $("#datepicker").val() != "") { /*logic goes here */ }
Upvotes: 27
Views: 84479
Reputation: 29849
The problem with getting the length
property on filter()
is that jQuery will evaluate every single element in the collection, just to populate a count when all we care about is whether the value is greater than zero.
None of the current answers and even jQuery's own .is()
, .has()
, and .filter()
make use of short circuiting as soon as the criteria is met.
You can define a simple extension method called .any()
like this:
jQuery.fn.any = function(filter){
for (i=0 ; i<this.length ; i++) {
if (filter.call(this[i])) return true;
}
return false;
};
And then pass in a filtering function like this:
var someInputsEmpty = $("#reference,#pin,#fName,#mName,#datepicker").any(function() {
return this.value == '';
});
jQuery.fn.any = function(filter){
for (i=0 ; i<this.length ; i++) {
if (filter.call(this[i])) return true;
}
return false;
};
$(function() {
var gotMatch = $(":input").any(function() {
return this.value == 'hi';
});
if (gotMatch) {
console.log("Hello to you too!");
} else {
console.log("Why don't you say Hi!");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
Upvotes: 6
Reputation: 160833
You could do like below:
if ($("#reference,#pin,#fName,#mName,#datepicker").filter(function() { return $(this).val(); }).length > 0) {
//..
}
Using a common function like the following would make it reusable:
function hasValue(elem) {
return $(elem).filter(function() { return $(this).val(); }).length > 0;
}
And you could call it like this:
hasValue("#my-input-id");
Upvotes: 61
Reputation: 7303
How about:
http://jsfiddle.net/lollero/rr2ss/1/
Another example: http://jsfiddle.net/lollero/rr2ss/12/
$(function() {
// Check value of each and every input element....
// Which you can of course change to be more specific, like: $('#myForm input')
$( "input" ).val(function( i, val ) {
// Return the console log IF value is not empty
// value=" " still counts as "not empty", because technically it isn't
// You could of course replace the console.log(); with anything you'd like
val && console.log('not empty: input-' + (++i) );
// Note that you don't have to return val if you don't want to, it's just for show in this case.
return val
});
});
Upvotes: 0