Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute script based on which option is selected in a select box?

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.


1 Answers

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
  }
});
like image 54
cgp Avatar answered Mar 02 '26 08:03

cgp