zii*_*web 93 javascript forms jquery
这是检查字段值是否为空的好方法吗?
if($('#person_data[document_type]').value() != 'NULL'){}
Run Code Online (Sandbox Code Playgroud)
或者,还有更好的方法?
Guf*_*ffa 155
字段的值不能为null,它始终是字符串值.
代码将检查字符串值是否为字符串"NULL".你想检查它是否是一个空字符串:
if ($('#person_data[document_type]').val() != ''){}
Run Code Online (Sandbox Code Playgroud)
要么:
if ($('#person_data[document_type]').val().length != 0){}
Run Code Online (Sandbox Code Playgroud)
如果要检查元素是否存在,则应在调用之前执行此操作val:
var $d = $('#person_data[document_type]');
if ($d.length != 0) {
if ($d.val().length != 0 ) {...}
}
Run Code Online (Sandbox Code Playgroud)
Fli*_*pke 37
我也会修剪输入字段,导致空间可能使它看起来像填充
if ($.trim($('#person_data[document_type]').val()) != '')
{
}
Run Code Online (Sandbox Code Playgroud)
dar*_*ioo 13
假设
var val = $('#person_data[document_type]').value();
Run Code Online (Sandbox Code Playgroud)
你有这些情况:
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)
Run Code Online (Sandbox Code Playgroud)
所以,用你需要的东西.
All*_*ara 11
这取决于你传递给条件的信息类型..
有时您的结果将是null或undefined或''或0,对于我的简单验证我使用此if.
( $('#id').val() == '0' || $('#id').val() == '' || $('#id').val() == 'undefined' || $('#id').val() == null )
Run Code Online (Sandbox Code Playgroud)
注意: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;
}
},
Run Code Online (Sandbox Code Playgroud)
利用这个助手实现这一目标.