Leem
Leem

Reputation: 18328

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

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.

Upvotes: 0

Views: 213

Answers (2)

Edgar Villegas Alvarado
Edgar Villegas Alvarado

Reputation: 18354

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';
    }
});

Upvotes: 1

hunter
hunter

Reputation: 63542

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/

Upvotes: 5

Related Questions