Detect when a specific <option> is selected with jQuery

39,783

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

Solution 2

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

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

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

Solution 4

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

Solution 5

$("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.

Share:
39,783
Philip Morton
Author by

Philip Morton

Updated on March 29, 2020

Comments

  • Philip Morton
    Philip Morton about 4 years

    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?

  • Gene Bo
    Gene Bo almost 10 years
    Since my option values were unique, I could use this : var val = $('#select_xyz').val(); And the mistake I was making before I saw this post - I was using click(..) when I should have used .change(..) . Thanks!