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

↘锁芯ラ 提交于 2019-12-21 21:33:50

问题


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:


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



回答2:


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


来源:https://stackoverflow.com/questions/1071992/execute-script-based-on-which-option-is-selected-in-a-select-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!