Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - Setting a select list option by id

Tags:

jquery

I feel like this should not be this complicated, but I'm sure I'm missing something trivial. Thanks for anyone that can help!

XSL:

<select id="mySelectList">
  <option id="1" description="Blue" />
  <option id="2" description="Black" />
  <option id="3" description="Green" />
</select>

JS:

$("#mySelectList option[id='1']").attr("selected", "selected");

EDIT: Fixed my select per Nick's response.

like image 785
SethPlante Avatar asked Nov 11 '10 21:11

SethPlante


People also ask

How can set the selected value of dropdown in jQuery using ID?

Using the jQuery change() method; you can set the selected value of dropdown in jquery by using id, name, class, and tag with selected html elements; see the following example for that: Example 1 :- Set selected value of dropdown in jquery by id.

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 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);


1 Answers

A <select> should look like:

<select id="mySelectList">

Or if you literally want the element and that's XML, remove the # for an element selector, like this:

$("mySelectList option[id='1']").attr("selected", "selected");
like image 133
Nick Craver Avatar answered Sep 30 '22 19:09

Nick Craver