Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when a specific <option> is selected with jQuery

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?

like image 932
Philip Morton Avatar asked Dec 23 '09 14:12

Philip Morton


People also ask

How do you check if any option is selected in jQuery?

$('#mySelectBox option'). each(function() { if ($(this). isChecked()) alert('this option is selected'); else alert('this is not'); });

How do you detect change in select?

To detect real-time changes, you want the input event. document. addEventListener('input', function (event) { // Only run on our select menu if (event.target.id !== 'wizard') return; // Do stuff... }, false);

How do I select a specific Dropdownlist using jQuery?

Syntax of jQuery Select Option$(“selector option: selected”); The jQuery select option is used to display selected content in the option tag. text syntax is below: var variableValue = $(“selector option: selected”).


2 Answers

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;   } }); 
like image 198
Ryan Avatar answered Oct 02 '22 19:10

Ryan


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

$('#type').change(function(){    if($(this).val() == 2){      /* Do Something */   } }); 
like image 28
Justin Swartsel Avatar answered Oct 02 '22 18:10

Justin Swartsel