Reputation: 400
So I got this selecter with an id of mySelect.
<select name="mySelect" id="mySelect">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
And if one of these options is selected I want to set the variable color in jquery to a value. And later use this color variable.
var color;
$('#mySelect option:selected').change(function(){
if($(this).val() == '1') {
color = #000080;
return color;
}
if($(this).val() == '2') {
color = #ff0000;
return color;
}
});
The jquery code is not correct and I can't seem to fix it..
Upvotes: 0
Views: 2198
Reputation: 370
You need this:
$(function()
{ $('#mySelect').on('change',function(){ if($(this).val()==1) { /*do stuff here*/ } }); });
live demo: http://jsfiddle.net/PwMxk/1/
Upvotes: 0
Reputation: 48445
The change event should be on the select
element, not on option:selected
, try this:
var color;
$('#mySelect').change(function(){
if($(this).val() == '1') {
color = "#000080";//<- Needs to be a string
return color;
}
});
Couple of things to note:
#mySelect
), though I assume that is a typo on your part?option:selected
for value
, though you would need this is you wanted to access the selected option
DOM element (e.g. to get the text
)return
statement, you should probably just remove thisAdvanced Solution
I would recommend that instead of using a set of if/else statements that you use an array to store your list of colours, you can then use the val()
as the index (don't forget to subtract 1 as it is zero based). Like this:
var colors = ["#000080", "#008000", "#800000"];
var color;
$('#mySelect').change(function () {
color = colors[$(this).val() - 1];
return color;
});
Upvotes: 3
Reputation: 894
Try this
var color;
$('#mySelect').change(function(){
switch($(this).val()) {
case "1": color = "#000080";break;
case "2": color = "#FF0080";break;
case "3": color = "#EE0080";break;
}
alert(color);
});
http://jsfiddle.net/Pesulap/cMLmU/1/
Upvotes: 0
Reputation: 56539
$('#categorie option:selected') // This is for selected option which won't work
// change event handler
Change it back to select tag
$('#mySelect').change(.. //also change your id
Upvotes: 0