【发布时间】:2011-05-13 18:34:49
【问题描述】:
这是检查字段值是否为null 的好方法吗?
if($('#person_data[document_type]').value() != 'NULL'){}
或者有没有更好的方法?
【问题讨论】:
-
#person_data 是什么元素?你认为什么是 NULL 值?
标签: javascript jquery forms
这是检查字段值是否为null 的好方法吗?
if($('#person_data[document_type]').value() != 'NULL'){}
或者有没有更好的方法?
【问题讨论】:
标签: javascript jquery forms
字段的值不能为空,它总是一个字符串值。
代码将检查字符串值是否为字符串“NULL”。你想检查它是否是一个空字符串:
if ($('#person_data[document_type]').val() != ''){}
或:
if ($('#person_data[document_type]').val().length != 0){}
如果你想检查元素是否存在,你应该在调用val之前完成:
var $d = $('#person_data[document_type]');
if ($d.length != 0) {
if ($d.val().length != 0 ) {...}
}
【讨论】:
The value of a field can not be null, it's always a string value. 这并不完全正确。我有一个 select 不包含 options。当我对此执行.val() 时,它返回null。 jQuery 1.7.2
option 元素的 select 不是您通常拥有的东西。太没用了。
<select> 可以包含您的用户的可能选项,其<option>s 将来自某种验证。
select 中提供占位符,它将以 null 值开始,因为选择了“禁用”选项。 stackoverflow.com/questions/5805059/…
if ($('#person_data[document_type]').val() !== null){}
我也会修剪输入字段,因为空格可能使它看起来像填充
if ($.trim($('#person_data[document_type]').val()) != '')
{
}
【讨论】:
假设
var val = $('#person_data[document_type]').value();
你有这些情况:
val === 'NULL'; // actual value is a string with content "NULL"
val === ''; // actual value is an empty string
val === null; // actual value is null (absence of any value)
所以,使用你需要的。
【讨论】:
这取决于你传递给条件的信息类型。
有时您的结果将是null 或undefined 或'' 或0,对于我的简单验证,我使用此 if。
( $('#id').val() == '0' || $('#id').val() == '' || $('#id').val() == 'undefined' || $('#id').val() == null )
注意:null != 'null'
【讨论】:
_helpers: {
//Check is string null or empty
isStringNullOrEmpty: function (val) {
switch (val) {
case "":
case 0:
case "0":
case null:
case false:
case undefined:
case typeof this === 'undefined':
return true;
default: return false;
}
},
//Check is string null or whitespace
isStringNullOrWhiteSpace: function (val) {
return this.isStringNullOrEmpty(val) || val.replace(/\s/g, "") === '';
},
//If string is null or empty then return Null or else original value
nullIfStringNullOrEmpty: function (val) {
if (this.isStringNullOrEmpty(val)) {
return null;
}
return val;
}
},
利用这个助手来实现。
【讨论】:
isStringNullOrEmpty 是isStringFalsey,因此return !val; 可以工作
jquery 提供val() 函数和not value()。您可以使用 jquery 检查空字符串
if($('#person_data[document_type]').val() != ''){}
【讨论】:
试试
if( this["person_data[document_type]"].value != '') {
console.log('not empty');
}
<input id="person_data[document_type]" value="test" />
【讨论】:
我的工作解决方案是
var town_code = $('#town_code').val();
if(town_code.trim().length == 0){
var town_code = 0;
}
【讨论】: