Jalpesh Patel
Jalpesh Patel

Reputation: 3188

how to get option index based on option text

i have try to find option index bases on option text. My HTML code is bellow.

<select multiple="multiple" onchange="dependentOptions.select(this); opConfig.reloadPrice();optionImages.showImage(this);" title="" class="multiselect product-custom-option" id="select_472" name="options[472][]" >
<option selected="selected" value="3364">Black </option>
<option selected="selected" value="3365">White </option>
<option value="3366">Cool Grey #9 </option>
<option value="3367">Red </option>
<option value="3368">Fire Red </option>
<option value="3369">Orange </option>
<option value="3370">Rich Yellow </option>
<option value="3371">Primrose Yellow </option>
<option value="3372">Light Green </option>
</select>

and my script is like this

jQuery("#select_472 select option:[text=Rich Yellow]").index();

but it return me -1 insted of 7

So please help me to sove this.

Upvotes: 1

Views: 805

Answers (3)

Sudharsan S
Sudharsan S

Reputation: 15393

The index should be began on 0 so the text 'Rich Yellow' be index position is 6.

$("#select_472 option[value='3370']").index();

$("#select_472 option:contains('Rich Yellow ')").index();

Fiddle

Upvotes: 2

A. Wolff
A. Wolff

Reputation: 74420

You could filter it (and trim text value), looks more safe:

jQuery("#select_472 option").filter(function(){
    return $.trim($(this).text()) === "Rich Yellow"
}).index();

Upvotes: 1

dfsq
dfsq

Reputation: 193261

You would use :contains pseudo-selector:

jQuery("#select_472 option:contains('Rich Yellow')").index();

Upvotes: 4

Related Questions