jQuery检查是否有任何文本输入有值
我想问一下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可以使其重用:
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'); } })
只需使用:
if (!$("#id").val().length == 0))
在filter()
上获取length
属性的问题是jQuery将评估集合中的每个元素,只是为了填充一个计数,当我们关心的是值是否大于零时。
当前的答案,甚至jQuery自己的.has()
和.filter()
不会在符合条件时立即使用短路。
您可以像这样定义一个名为.any()
的简单扩展方法:
jQuery.fn.any = function(filter){ for (i=0 ; i
然后传入这样的过滤函数:
var someInputsEmpty = $("#reference,#pin,#fName,#mName,#datepicker").any(function() { return this.value == ''; });
jQuery.fn.any = function(filter){ for (i=0 ; i
怎么样:
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 }); });