Why I can not get the correct value of my <sele

2019-09-02 09:34发布

问题:

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/