jQuery检查是否有任何文本输入有值 [英] jQuery check if any text input has value

查看:109
本文介绍了jQuery检查是否有任何文本输入有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问一下jQuery中是否有更好的方法来选择多个文本输入,然后检查它们中是否有值。这是我的代码:

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 */ }


推荐答案

你可以这样做:

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;
}

您可以这样称呼它:

hasValue("#my-input-id");

这篇关于jQuery检查是否有任何文本输入有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆