How to check 'undefined' value in jQuery

后端 未结 11 566
慢半拍i
慢半拍i 2020-12-12 11:49

Possible Duplicate:
Detecting an undefined object property in JavaScript
javascript undefined compare

H

相关标签:
11条回答
  • 2020-12-12 11:58

    You can use two way 1) if ( val == null ) 2) if ( val === undefine )

    0 讨论(0)
  • 2020-12-12 12:00

    JQuery library was developed specifically to simplify and to unify certain JavaScript functionality.

    However if you need to check a variable against undefined value, there is no need to invent any special method, since JavaScript has a typeof operator, which is simple, fast and cross-platform:

    if (typeof value === "undefined") {
        // ...
    }
    

    It returns a string indicating the type of the variable or other unevaluated operand. The main advantage of this method, compared to if (value === undefined) { ... }, is that typeof will never raise an exception in case if variable value does not exist.

    0 讨论(0)
  • 2020-12-12 12:03
    function isValue(value, def, is_return) {
        if ( $.type(value) == 'null'
            || $.type(value) == 'undefined'
            || $.trim(value) == ''
            || ($.type(value) == 'number' && !$.isNumeric(value))
            || ($.type(value) == 'array' && value.length == 0)
            || ($.type(value) == 'object' && $.isEmptyObject(value)) ) {
            return ($.type(def) != 'undefined') ? def : false;
        } else {
            return ($.type(is_return) == 'boolean' && is_return === true ? value : true);
        }
    }
    

    try this~ all type checker

    0 讨论(0)
  • 2020-12-12 12:06

    You can use shorthand technique to check whether it is undefined or null

     function A(val)
     {
       if(val || "") 
       //do this
     else
     //do this
     }
    

    hope this will help you

    0 讨论(0)
  • 2020-12-12 12:07

    If you have names of the element and not id we can achieve the undefined check on all text elements (for example) as below and fill them with a default value say 0.0:

    var aFieldsCannotBeNull=['ast_chkacc_bwr','ast_savacc_bwr'];
     jQuery.each(aFieldsCannotBeNull,function(nShowIndex,sShowKey) {
       var $_oField = jQuery("input[name='"+sShowKey+"']");
       if($_oField.val().trim().length === 0){
           $_oField.val('0.0')
        }
      })
    
    0 讨论(0)
  • 2020-12-12 12:08

    when I am testing "typeof obj === undefined", the alert(typeof obj) returning object, even though obj is undefined. Since obj is type of Object its returning Object, not undefined.

    So after hours of testing I opted below technique.

    if(document.getElementById(obj) !== null){
    //do...
    }else{
    //do...
    }
    

    I am not sure why the first technique didn't work.But I get done my work using this.

    0 讨论(0)
提交回复
热议问题