Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery – Select optgroup in select

I have a select with 2 optgroups. Is there a way to call an function only if an option from the first optgroup is selected and call another function if an option from the second optgroup is selected?

like image 605
user495915 Avatar asked Mar 29 '11 15:03

user495915


2 Answers

Sure.

HTML:

What is your preferred vacation spot?<br>
<SELECT ID="my_select"> 

<OPTGROUP LABEL="OptGroup One." id="one">        
<OPTION LABEL="Florida">Florida</OPTION>         
<OPTION LABEL="Hawaii">Hawaii</OPTION>         
<OPTION LABEL="Jersey">Jersey Shore</OPTION>    
</OPTGROUP> 

<OPTGROUP LABEL="OptGroup Two" id="two">  
<OPTION LABEL="Paris">Paris</OPTION>  
<OPTION LABEL="London">London</OPTION> 
<OPTION LABEL="Florence">Florence</OPTION>  
</OPTGROUP>

</SELECT>

JS:

$("#my_select").change(function(){
    var selected = $("option:selected", this);
    if(selected.parent()[0].id == "one"){
        //OptGroup 1, do something here..
    } else if(selected.parent()[0].id == "two"){
        //OptGroup 2, do something here
    }
});

Example here: http://jsfiddle.net/pyG2v/

like image 135
mattsven Avatar answered Oct 01 '22 02:10

mattsven


$('#selectID').change(function(){
  var $option = $('option:selected', this); // get selected option
  var optGroup = $option.closest('optgroup').index(); // get which optgroup
  if(optGroup == 0){
    // first
  }
  else if(optGroup == 1){
    // second
  }
  else{
    // not first or second
  }
});
like image 21
Rocket Hazmat Avatar answered Oct 01 '22 02:10

Rocket Hazmat