jquery 如果文本输入不*不*等于空白
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8095822/
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
jquery if text input does *not* equal blank
提问by Adi
I am trying to work out how to do something if a certain text box is notempty (i.e. contain something, could be anything)
如果某个文本框不为空(即包含某些内容,可以是任何内容),我正在尝试弄清楚如何做某事
This is my code (that doesnt seem to work)
这是我的代码(似乎不起作用)
if ( !($('#edit-sPostalCode').attr('val','')) ) {
stuff here
}
What have I missed?
我错过了什么?
回答by El Ronnoco
if ( $('#edit-sPostalCode').val() != '' ) {
stuff here
}
$('#edit-sPostalCode').attr('val','')
will actually create an attribute of the input box with a value of ''
and will then return a jQuery object.
$('#edit-sPostalCode').attr('val','')
实际上将创建一个值为 的输入框的属性,''
然后将返回一个 jQuery 对象。
Saying !($('#edit-sPostalCode').attr('val',''))
will then negate that jQuery object. As an instance of an object is truthyin JS the result of this expression will always be false
.
Saying!($('#edit-sPostalCode').attr('val',''))
然后将否定该 jQuery 对象。由于对象的实例在 JS 中是真实的,因此该表达式的结果将始终为false
.
回答by Blazemonger
Are you aware of the .val
method?
你知道.val
方法吗?
if ( $('#edit-sPostalCode').val() !== '' ) {
Although you ought to $.trim
the value if you consider whitespace as being equivalent to nothing at all:
尽管$.trim
如果您认为空格等于什么都没有,则应该考虑该值:
if ( $.trim( $('#edit-sPostalCode').val() ) !== '' ) {
回答by Nicholas Murray
if ( !($('#edit-sPostalCode').val() === '') ) {
stuff here
}