ques-1vdjyj4n

Search A2Z 24

Question : How to use JQuery to select the nth option?

I have the following HTML

<select name="pqr" id="xyz">
  <option value="">--Select--</option>
  <option value="Hi">Hi</option>
  <option value="Hello">Hello</option>
  <option value="Hey">Hey</option>
  <option value="Ok">Ok</option>
</select>

May I know,how I can select 2nd option ?

asked July 28, 2015

1 Answers

Dispalying 1 to 1 of 1 |

There are many way in javascript/jQuery.

1. By using jQuery :eq() Selector :

$("select#xyz option:eq(2)").attr("selected", "selected");

jQuery( ":eq(index)" )
index: Zero-based index of the element to match.
jQuery( ":eq(-index)" )
-index or indexFromEnd: Zero-based index of the element to match, counting backwards from the last element.
Description: Select the element at index n within the matched set.

2. By using jQuery :contains() Selector :
If you want to choose option on the base of value then :

$("select#xyz option:contains('Hi')").attr("selected", "selected");

jQuery( ":contains(text)" )
text: A string of text to look for. It's case sensitive.
Description: Select all elements that contain the specified text.
The matching text can appear directly within the selected element, in any of that element's descendants, or a combination thereof. As with attribute value selectors, text inside the parentheses of :contains() can be written as a bare word or surrounded by quotation marks.
The text must have matching case to be selected.

See comments (0) | Comment
Answered 2 Years ago
Dispalying 1 to 1 of 1 |

Write your Answer write code <pre class="brush: xml">---code---</pre>

Login as a member to access answering block !! click-here
loading...

Reveal Modal Goodness

This is a default modal in all its glory, but any of the styles here can easily be changed in the CSS.

This is just a simple modal with the default styles, but any type of content can live in here. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi quis sem vel enim eleifend tristique. Etiam tincidunt faucibus pharetra.

×