Detect when a specific <option> is selected with jQuery

雨燕双飞 提交于 2019-12-18 10:40:49

问题


I'd like jQuery to detect when the option with the id trade_buy_max is selected.

$(document).ready(function() {
    $("option#trade_buy_max").select(function () {
        //do something
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<select name='type' id='type'>
    <option id='trade_buy' value='1' selected='selected'>Buy</option>
    <option id='trade_buy_max' value='1'>Buy max</option>
    <option id='trade_sell' value='2'>Sell</option>
    <option id='trade_sell_max' value='2'>Sell max</option>
</select>

I've tried the following, but it doesn't seem to work.

Any ideas?


回答1:


This works... Listen for the change event on the select box to fire and once it does then just pull the id attribute of the selected option.

$("#type").change(function(){
  var id = $(this).find("option:selected").attr("id");

  switch (id){
    case "trade_buy_max":
      // do something here
      break;
  }
});



回答2:


What you need to do is add an onchange handler to the select:

$('#type').change(function(){ 
  if($(this).val() == 2){
     /* Do Something */
  }
});



回答3:


you can bind change event on its select instead, then check if option selected

$("select#type").change(function () {
   if( $("option#trade_buy_max:selected").length )
   {
     // do something here
   }
});



回答4:


$("option#trade_buy_max").change(function () {
    opt = $(this).children("option:selected").attr('id');
    if(opt == '#trade_sell_max'){
        // do stuff
    } 
});

Untested, but that should work.




回答5:


Use the change event and get the id attribute of the selected option:

$('#type').change(function () {
  var selectedId = $('option:selected', this).attr('id');

  if (selectedId == "trade_buy_max") {
    // do something
  }
});



回答6:


Change .select to .change and put space before #



来源:https://stackoverflow.com/questions/1953063/detect-when-a-specific-option-is-selected-with-jquery

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