views:

487

answers:

2

I've got a select box where the user selects which elements they want to see based on option 1, option 2 and option 3.

So what I'm trying to set up is have if option 1 is selected run one set of commands and if option 2 run another and so on.

I guess I just need to know how to set up the jQuery selector.

A: 

Give options 1 and 2 unique ids. Example:

<option id="option1">
<option id="option2">

And then the jQuery selectors would be:

$("#option1")
$("#option2")

respectively.

To check which one is selected via jQuery:

if($("#option1:selected").length)) {

 // If option 1 is selected

}

else if($("#option2:selected").length)) {

 // If option 2 is selected

}
gclaghorn
+3  A: 

You didn't specify how the code was triggered, so here are two common ways:

$('#yourSelect').change(function() {
  if ($(this).val() == 'something') { 
     // do this
  }
  if ($(this).val() == 'somethingelse') { 
     // do that
  }
});

Note that while I used the onchange event for the select, an onclick for another element would look like this instead:

$('#somethingelse').click(function() {
  if ($('#yourselect').val() == 'something') { 
     // do this
  }
  if ($('#yourselect').val() == 'somethingelse') { 
     // do that
  }
});
altCognito
Consider using a switch() statement to increase readability
Mike Robinson