简体   繁体   中英

typeof not working for undefined type

basically i am checking if i get some selected id then use that selected value, otherwise use value from different attribute, at times it happens there is no selected Item so i get undefined, but following code dont solve my problem

var user_role = $('#user_role option:selected').attr('id');
        if (typeof user_role === 'undefined') {
            alert(intval(jQuery('#selected_role').val()));
            user_role = jQuery('#selected_role').val();
        }

i have also tried

var user_role = $('#user_role option:selected').attr('id');
        if (typeof user_role === undefined) {
            alert(intval(jQuery('#selected_role').val()));
            user_role = jQuery('#selected_role').val();
        }

EDIT: For those asking me to check if(!user_role ) i have already check it and it dont work In either of the above way i am not getting into my if condition.

Your undefined detection works fine. The "problem" is, that if nothing is selected, option:selected returns the first option, hence typeof .attr('id') is never "undefined" .

 var user_role = $('#user_role option:selected').attr('id'); document.body.innerHTML += user_role; 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <select id="user_role"> <option id="opt1">Opt1</option> <option id="opt2">Opt3</option> <option id="opt3">Opt3</option> </select> 

(If you omitted all the option s or id s of options, you could enter the if .)

The best way to check if something is a jQuery object (so you don't get any undefined errors) is like this:

var user_role = $('#user_role option:selected').attr('id');
if (!user_role) {
     alert(intval(jQuery('#selected_role').val()));
     user_role = intval(jQuery('#selected_role').val());
}

undefined is an object(not a type) try this:

if (user_role === undefined)
{}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM