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 */ }
How about:
http://jsfiddle.net/lollero/rr2ss/1/
Another example: http://jsfiddle.net/lollero/rr2ss/12/
Try jQuery each()
You could do like below:
Using a common function like the following would make it reusable:
And you could call it like this:
The problem with getting the
length
property onfilter()
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:And then pass in a filtering function like this:
Further Reading:
Just use this: