jQuery 检查 <input> 是否存在并有值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15481539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:09:26  来源:igfitidea点击:

jQuery check if <input> exists and has a value

javascriptjquery

提问by Dimskiy

I have the following example:

我有以下示例:

<input type="text" class="input1" value="bla"/>

Is there a way to check if this element exists and has a value in one statement? Or, at least, anything shorter then

有没有办法检查此元素是否存在并且在一个语句中具有值?或者,至少,任何更短的时间

if($('.input1').length > 0 && $('input1').val() != '')

Just getting frustrated here with mile-long conditions.

只是在这里遇到一英里长的条件而感到沮丧。

回答by Brian

The input won't have a value if it doesn't exist. Try this...

如果输入不存在,则输入将没有值。尝试这个...

if($('.input1').val())

回答by Curt

You could do:

你可以这样做:

if($('.input1').length && $('.input1').val().length)

lengthevaluates to falsein a condition, when the value is 0.

lengthfalse当值为 时,在条件中计算为0

回答by 97ldave

You can do something like this:

你可以这样做:

jQuery.fn.existsWithValue = function() { 
    return this.length && this.val().length; 
}

if ($(selector).existsWithValue()) {
        // Do something
}

回答by Benmj

Just for the heck of it, I tracked this down in the jQuery code. The .val() function currently starts at line 165 of attributes.js. Here's the relevant section, with my annotations:

只是为了它,我在 jQuery 代码中跟踪了它。.val() 函数当前从attributes.js 的第 165 行开始。这是相关部分,带有我的注释:

val: function( value ) {
    var hooks, ret, isFunction,
        elem = this[0];

        /// NO ARGUMENTS, BECAUSE NOT SETTING VALUE
    if ( !arguments.length ) {

        /// IF NOT DEFINED, THIS BLOCK IS NOT ENTERED. HENCE 'UNDEFINED'
        if ( elem ) {
            hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];

            if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
                return ret;
            }

            ret = elem.value;

            /// IF IS DEFINED, JQUERY WILL CHECK TYPE AND RETURN APPROPRIATE 'EMPTY' VALUE
            return typeof ret === "string" ?
                // handle most common string cases
                ret.replace(rreturn, "") :
                // handle cases where value is null/undef or number
                ret == null ? "" : ret;
        }

        return;
    }

So, you'll either get undefinedor ""or null-- all of which evaluate as false in if statements.

所以,你要么得到undefinedor""要么null- 所有这些在 if 语句中都被评估为假。

回答by KyleMit

You can create your own custom selector:hasValueand then use that to find, filter, or test any other jQuery elements.

您可以创建自己的自定义选择器:hasValue,然后使用它来查找、过滤或测试任何其他 jQuery 元素。

jQuery.expr[':'].hasValue = function(el,index,match) {
  return el.value != "";
};

Then you can find elements like this:

然后你可以找到这样的元素:

var data = $("form input:hasValue").serialize();

Or test the current element with .is()

或测试当前元素 .is()

var elHasValue = $("#name").is(":hasValue");

jQuery.expr[':'].hasValue = function(el) {
  return el.value != "";
};


var data = $("form input:hasValue").serialize();
console.log(data)


var elHasValue = $("[name='LastName']").is(":hasValue");
console.log(elHasValue)
label { display: block; margin-top:10px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
  <label>
    First Name:
    <input type="text" name="FirstName" value="Frida" />
  </label>

  <label>
    Last Name:
    <input type="text" name="LastName" />
  </label>
</form>

Further Reading:

进一步阅读

回答by Mirza Arsal Chaudhry

if($('#user_inp').length > 0 && $('#user_inp').val() != '')
{

    $('#user_inp').css({"font-size":"18px"});
    $('#user_line').css({"background-color":"#4cae4c","transition":"0.5s","height":"2px"});
    $('#username').css({"color":"#4cae4c","transition":"0.5s","font-size":"18px"});

}

回答by BWP

I would do something like this: $('input[value]').something. This finds all inputs that have value and operates something onto them.

我会做这样的事情:$('input[value]').something。这会找到所有有价值的输入并对它们进行操作。