Search code examples
jquerybootstrap-select

$(select).val().length of null gives error


I have a select object in my form, styled using Bootstrap-select.js plug-in. When I initialize the select box, and I try to get the value of it, it is null until I select an option. In my script I am using:-

$(select).val().length

However, this gives an error when $(select).val() is null. I would really like to get a 0.

How do I do this?


Solution

  • try:-

    ($(select).val() || '').length
    

    Logical Operators

    Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.

    Examples of expressions that can be converted to false are:

    • null
    • NaN
    • 0
    • empty string ("")
    • NaN
    • undefined

    Demo

    var length = ($('select').val() || '').length;
    
    console.log('length: ' + length);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <select>
    
    <select>