Nijn
Nijn

Reputation: 400

Change variable if option is selected

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

Answers (4)

You need this:

$(function() { $('#mySelect').on('change',function(){ if($(this).val()==1) { /*do stuff here*/ } }); });

live demo: http://jsfiddle.net/PwMxk/1/

Upvotes: 0

musefan
musefan

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:

  1. I have changed the selector to use the correct ID (#mySelect), though I assume that is a typo on your part?
  2. You don't actually need to use 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)
  3. I fixed your color string (see comments above)
  4. Not sure why you are using a return statement, you should probably just remove this

Here is a working example

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

Here is an example

Upvotes: 3

Pesulap
Pesulap

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

Praveen
Praveen

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

Related Questions