代码之家  ›  专栏  ›  技术社区  ›  tirenweb

jQuery:检查字段值是否为空

  •  87
  • tirenweb  · 技术社区  · 14 年前

    这是检查字段值是否为 null ?

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

    还是有更好的办法?

    7 回复  |  直到 5 年前
        1
  •  158
  •   Guffa    14 年前

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

    代码将检查字符串值是否为字符串“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 ) {...}
    }
    
        2
  •  37
  •   Flipke    14 年前

    我还将修剪输入字段,因为空格可以使其看起来像填充的

    if ($.trim($('#person_data[document_type]').val()) != '')
    {
    
    }
    
        3
  •  13
  •   darioo    14 年前

    假设

    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)
    

    所以,用你需要的。

        4
  •  11
  •   Wirone Allan Felipe Murara    8 年前

    这取决于你将什么样的信息传递给条件。。

    有时你的结果会是 null undefined '' 0 ,对于我的简单验证,我使用这个if。

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

    注意 : 无效的 != 'null'

        5
  •  6
  •   Nilesh Moradiya    9 年前
    _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;
            }
        },
    

    利用这些助手来实现这一点。

        6
  •  0
  •   Chinmayee G    14 年前

    jquery提供 val() 功能和 not value() . 可以使用jquery检查空字符串

    if($('#person_data[document_type]').val() != ''){}
    
        7
  •  0
  •   Kamil Kiełczewski    5 年前

    尝试

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