Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of select option in an optgroup with jquery

I have the following select:

<select name="end" id="end"> 
    <optgroup label="Morning"> 
        <option value="12:00a">12:00 am</option> 
        <option value="12:30a">12:30 am</option> 
        <option value="1:00a">1:00 am</option> 
        <option value="1:30a">1:30 am</option> 
    </optgroup> 
    <optgroup label="Evening"> 
        <option value="12:00p">12:00 pm</option> 
        <option value="12:30p">12:30 pm</option> 
        <option value="1:00p" selected="selected">1:00 pm</option> 
        <option value="1:30p">1:30 pm</option> 
    </optgroup> 
</select> 

I need to find the overall index of the selected option, but the optgroup is making that difficult. In other words, the selected one should return 6, but it is returning 2. I tried this:

var idx = $('#end :selected').prevAll().size();

But that returns the index within that optgroup, not the overall index. I can't change the format or values of the select options.

like image 690
Tauren Avatar asked Feb 09 '10 00:02

Tauren


4 Answers

Erm... whyever not good old DOM methods? For a single-select:

var idx= document.getElementById('end').selectedIndex;

// or $('#end')[0].selectedIndex if you must

Or, which will also work on multi-selects, get the option element node you're interested in and fetch option.index on it.

This is massively faster and simpler than getting jQuery to process complex selectors.

like image 88
bobince Avatar answered Nov 01 '22 06:11

bobince


Use the index() function to find an element within a set. Construct a set of all the options using $("#end option"). Find the selected option using the :selected pseudo-element. Note: indexes are 0-based.

var options = $("#end option");
var idx = options.index(options.filter(":selected"));
like image 30
cletus Avatar answered Nov 01 '22 06:11

cletus


You can also try this:

$('#end option:selected').prop('index')

This worked for me. The attr('selectedIndex') only brought up undefined with the select list.

like image 3
Harry Avatar answered Nov 01 '22 04:11

Harry


The same thing in jquery way is also short and simple:

var idx = $('#end').attr('selectedIndex');
like image 2
Csaba Avatar answered Nov 01 '22 04:11

Csaba