问题
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 */ }
回答1:
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");
回答2:
Try jQuery each()
$('input[type=text]').each(function(){
var text_value=$(this).val();
if(text_value!='')
{
console.log('Value exist');
}
})
回答3:
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="">
Further Reading:
- Jquery check form to see if any inputs has value
- Is there an "exists" function for jQuery?
- Jquery check form to see if any inputs has value
回答4:
Just use this:
if (!$("#id").val().length == 0))
回答5:
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
});
});
来源:https://stackoverflow.com/questions/22294112/jquery-check-if-any-text-input-has-value