Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you select a particular option in a SELECT element in jQuery?

Tags:

jquery

If you know the Index, Value or Text. also if you don't have an ID for a direct reference.

This, this and this are all helpful answers.

Example markup

<div class="selDiv">   <select class="opts">     <option selected value="DEFAULT">Default</option>     <option value="SEL1">Selection 1</option>     <option value="SEL2">Selection 2</option>   </select> </div> 
like image 599
Jay Corbett Avatar asked Nov 24 '08 16:11

Jay Corbett


People also ask

How do I select a specific Dropdownlist using jQuery?

Syntax of jQuery Select Option$(“selector option: selected”); The jQuery select option is used to display selected content in the option tag. text syntax is below: var variableValue = $(“selector option: selected”).

How do I select an option in select tag?

The select tag in HTML is used to create a dropdown list of options that can be selected. The option tag contains the value that would be used when selected. The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute.

How do I select a selected box using jQuery?

You can select on any attribute and its value by using the attribute selector [attributename=optionalvalue] , so in your case you can select the option and set the selected attribute. $("div. id_100 > select > option[value=" + value + "]"). prop("selected",true);


2 Answers

A selector to get the middle option-element by value is

$('.selDiv option[value="SEL1"]') 

For an index:

$('.selDiv option:eq(1)') 

For a known text:

$('.selDiv option:contains("Selection 1")') 

EDIT: As commented above the OP might have been after changing the selected item of the dropdown. In version 1.6 and higher the prop() method is recommended:

$('.selDiv option:eq(1)').prop('selected', true) 

In older versions:

$('.selDiv option:eq(1)').attr('selected', 'selected') 

EDIT2: after Ryan's comment. A match on "Selection 10" might be unwanted. I found no selector to match the full text, but a filter works:

 $('.selDiv option')     .filter(function(i, e) { return $(e).text() == "Selection 1"}) 

EDIT3: Use caution with $(e).text() as it can contain a newline making the comparison fail. This happens when the options are implicitly closed (no </option> tag):

<select ...> <option value="1">Selection 1 <option value="2">Selection 2    : </select> 

If you simply use e.text any extra whitespace like the trailing newline will be removed, making the comparison more robust.

like image 66
Grastveit Avatar answered Oct 08 '22 08:10

Grastveit


None of the methods above provided the solution I needed so I figured I would provide what worked for me.

$('#element option[value="no"]').attr("selected", "selected"); 
like image 24
user1074546 Avatar answered Oct 08 '22 10:10

user1074546