2010-11-22 108 views
74

这是检查字段值是否为空的好方法吗?jQuery:检查字段的值是否为空(空)

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

或者还有更好的方法吗?

+1

什么样的元素是#person_data?你认为什么是NULL值? – 2010-11-22 10:45:52

回答

123

一个字段的值不能为空,它总是一个字符串值。

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

'一个字段的值不能为空,它总是一个字符串值。“这并不完全正确。我有一个'select'不包含'options'。当我对此执行'.val()'时,它返回'null'。 Jquery 1.7.2 – Liam 2013-01-14 11:07:59

+1

@李安:是的,你说得对,这似乎是个例外。 – Guffa 2013-01-14 12:21:05

+1

这个异常是否在最新版本中解决? – 2014-01-30 21:09:52

0

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

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

我还要修剪输入字段检查空字符串,导致空间可以使它看起来像充满

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

} 
+0

完美的是我的工作:) – 2017-01-09 17:53:45

11

假设

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) 

因此,使用你需要的。

9

取决于你传递给有条件什么样的信息..

有时你的结果将是nullundefined''0,我简单的验证我用这个当。

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

注意null = 'null'

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

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