Why I can not get the correct value of my <select> field?

此生再无相见时 提交于 2019-12-11 18:08:00

问题


In my index.html, I have a selection drop down menu:

<select id="car">
    <option value="bmw">BMW</option>
    <option value="toyota">TOYOTA</option>
</select>

My js:

var c = $('#car');

var selection;

c.change(function(){

    if(c.val()==='bmw'){

        selection = 'BMW';

    }else if(c.val()==='toyota'){

        selection = 'TOYOTA';

    }

});

console.log(c.val());
console.log(selection);

When page firstly loaded, the initial selection is BMW, and I got console output "BMW" which is fine, then I select "TOYOTA", but the two console outputs are still "BMW".

How to get the current value of the selection outside jQuery .change(...) function after the selection has been changed??

________________typo have been fixed____________

car.val() and Selection are both my typo here in the post, in my code I do use selection, and c.val().

My point is how to get the current selection value out side jQuery change() function. Please do not discuss on my typo any more. Thank you.


回答1:


You should define your var selection with lowercase, as this:

var selection;

Why? Javascript is case sensitive, so, Sensitive and sensitive are distinct variables.

Also, you should define your car var, like this:

var selection;
c.change(function(){
    var car = $(this); //declare it
    if(car.val()==='bmw'){
        selection = 'BMW';
    }else if(car.val()==='toyota'){
        selection = 'TOYOTA';
    }
});



回答2:


You're looking at car when you should be using c. car does not have a val() method.

if(c.val()==='bmw'){

    selection = 'BMW';

} else if(c.val()==='toyota'){

    selection = 'TOYOTA';
}

Also note that var Selection; will not be the same variable as selection (lowercase).


A better approach might be:

c.change(function(){
    selection = c.find(":selected").text();
});

working example: http://jsfiddle.net/hunter/XespU/



来源:https://stackoverflow.com/questions/5898480/why-i-can-not-get-the-correct-value-of-my-select-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!