1

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.

Jalpesh Patel
  • 3,150
  • 10
  • 44
  • 68

3 Answers3

4

You would use :contains pseudo-selector:

jQuery("#select_472 option:contains('Rich Yellow')").index();
dfsq
  • 191,768
  • 25
  • 236
  • 258
2

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

Sudharsan S
  • 15,336
  • 3
  • 31
  • 49
  • 1
    `based on option text`. You're going off the value and not the text. – Ben Fortune Oct 31 '14 at 11:52
  • The one involving the "value = ..." is exactly what I have been looking for. All other answers on SO, some of them very clever, that I have found to achieve this task appear to use brute force looping through the options. But your way of getting the index from the value (apparently) doesn't. I therefore plussed you despite this not answering the OP's specific question! – mike rodent Aug 10 '17 at 18:12
1

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

jQuery("#select_472 option").filter(function(){
    return $.trim($(this).text()) === "Rich Yellow"
}).index();
A. Wolff
  • 74,033
  • 9
  • 94
  • 155