Get select box value of a particular index in jQuery

88 Views Asked by At

I have a Select Box where multiple option can be selected. Now I would like to get value of a particular index. How can I do this? For example I have a select box which have following values:

0 - Apple 1 - Orange 2 - Banana 3 - Pineapple

Now I would like to get value of index 2 which is Banana. How can I do this in jQuery?

1

There are 1 best solutions below

0
matthias_h On BEST ANSWER

If the select box has the same values for value and text, you can get the value for the 2nd select using eq() and val() like this:

console.log($("select option:eq(2)").val());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
  <option value="Apple">Apple</option>
  <option value="Orange">Orange</option>
  <option value="Banana">Banana</option>
  <option value="Pineapple">Pineapple</option>
</select>

If the select has numeric values and text, you can get the text "Banana" using eq() and text():

console.log($("select option:eq(2)").text());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
  <option value="0">Apple</option>
  <option value="1">Orange</option>
  <option value="2">Banana</option>
  <option value="3">Pineapple</option>
</select>

And in case you want to get the value of the option with the text "Banana" you can do this using filter():

console.log($("select option").filter(function () { return $(this).html() == "Banana"; }).val());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
  <option value="0">Apple</option>
  <option value="1">Orange</option>
  <option value="2">Banana</option>
  <option value="3">Pineapple</option>
</select>