[英]jQuery check if any text input has value
我想問一下jQuery中是否有更好的方法來選擇多個文本輸入,然后檢查它們中是否有值。 這是我的代碼:
if ($("#reference").val() != "" || $("#pin").val() != "" || $("#fName").val() != "" || $("#mName").val() != "" || $("#datepicker").val() != "") { /*logic goes here */ }
你可以這樣做:
if ($("#reference,#pin,#fName,#mName,#datepicker").filter(function() { return $(this).val(); }).length > 0) {
//..
}
使用如下的常用功能可以使其重用:
function hasValue(elem) {
return $(elem).filter(function() { return $(this).val(); }).length > 0;
}
你可以像這樣稱呼它:
hasValue("#my-input-id");
嘗試jQuery each()
$('input[type=text]').each(function(){
var text_value=$(this).val();
if(text_value!='')
{
console.log('Value exist');
}
})
在filter()
上獲取length
屬性的問題是jQuery將評估集合中的每個元素,只是為了填充一個計數,當我們關心的是值是否大於零時。
目前的答案都不對,甚至jQuery的自己.is()
.has()
和.filter()
一旦條件滿足利用短路。
您可以像這樣定義一個名為.any()
的簡單擴展方法:
jQuery.fn.any = function(filter){
for (i=0 ; i<this.length ; i++) {
if (filter.call(this[i])) return true;
}
return false;
};
然后傳入這樣的過濾函數:
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="">
只要用這個:
if (!$("#id").val().length == 0))
怎么樣:
http://jsfiddle.net/lollero/rr2ss/1/
另一個例子: 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
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.