2010-11-22 120 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; 
     } 
    }, 

利用這個助手實現這一目標。