jQuery:检查字段的值是否为null(空)

时间:2010-11-22 10:43:22

标签: javascript jquery forms

这是检查字段值是null吗?

的好方法
if($('#person_data[document_type]').value() != 'NULL'){}

或者有更好的方法吗?

8 个答案:

答案 0 :(得分:146)

字段的值不能为null,它始终是字符串值。

代码将检查字符串值是否为字符串“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 ) {...}
}

答案 1 :(得分:36)

我还会修剪输入字段,导致空格可能使其看起来像填充

if ($.trim($('#person_data[document_type]').val()) != '')
{

}

答案 2 :(得分:12)

假设

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)

所以,使用你需要的东西。

答案 3 :(得分:10)

取决于您传递给条件的信息类型。

有时您的结果会是nullundefined''0,对于我的简单验证,我会使用此结果。

( $('#id').val() == '0' || $('#id').val() == '' || $('#id').val() == 'undefined' || $('#id').val() == null )

注意null!= 'null'

答案 4 :(得分:6)

_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;
        }
    },

利用这些助手实现这一目标。

答案 5 :(得分:0)

jquery提供val()函数和not value()。您可以使用jquery

检查空字符串
if($('#person_data[document_type]').val() != ''){}

答案 6 :(得分:0)

尝试

if( this["person_data[document_type]"].value != '') { 
  console.log('not empty');
}
<input id="person_data[document_type]" value="test" />

答案 7 :(得分:0)

我的工作解决方案是

var town_code = $('#town_code').val(); 
 if(town_code.trim().length == 0){
    var town_code = 0;
 }