简体   繁体   中英

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.

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
  }
});
<select onchange="if(this.value)window[this.value]();">
<option value="">select one...
<option value="runme1">run me 1
<option value="runme2">run me 2
</select>

<script>
function runme1() {
alert(1);
}
function runme2() {
alert(2);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM