如何使用jQuery选择空输入(value ="") [英] How to select empty inputs (value="") using jQuery

查看:113
本文介绍了如何使用jQuery选择空输入(value ="")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在一个部分中检查( required )输入字段的空值,然后使用jQuery在事件上为它们添加一个类?到目前为止,我已经尝试过:

How can I check for empty values of (required) input fields within a section, and then add a class to them on an event, using jQuery? So far, I have tried:

jQuery("#sender_container input.required").val("").addClass("error");

但这似乎 SET 值,而不是检查它。有什么想法吗?

But that seems to SET the value, rather than checking it. Any ideas?

推荐答案

jQuery("#sender_container input.required").filter(function() {
    return !this.value;
}).addClass("error");​






为什么你必须使用过滤器而不是 [value = ] 您可以在 此演示 中看到


Why you have to use filter and not [value=""] you can see in this DEMO

原因是:属性选择器检查元素的初始状态,而不是当前状态。 (请注意,您可以使用 attr 功能更改初始状态,但这是不好的做法,您应该始终使用 prop

The reason is: attribute selectors check the initial state of the element, not the current state. (note that you can change the "initial" state with the attr function, but it's bad practice, you should always use prop)

因此,如果更改输入值,则当前值不会影响属性选择器。不明智...... :)

So if you change the input value, the current value won't effect the attribute selector. not wise... :)

注意:


  • .val() 返回表单元素的值,并打破jQuery链,
    $('selector')。val()。addClass('foo') 错误,返回值是一个字符串\\ \\ 数字

  • .val() returns the value of the form element, and breaks the jQuery chain, $('selector').val().addClass('foo') Error, the return value is a string\ number

.val(valueToSet) 设置表单元素的值,并且不会破坏jQuery链。

$('selector')。val(some value)。addClass('foo') - 有效,返回的值是jQuery

.val(valueToSet) sets the value of the form element and doesn't break the jQuery chain.
$('selector').val("some value").addClass('foo') - Valid, the returned value is a jQuery

这篇关于如何使用jQuery选择空输入(value ="")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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