Justin Meltzer
Justin Meltzer

Reputation: 13548

How do you set the selected element of a select html element with jQuery?

I have a <select> html element and I have users create the objects that are then dynamically included in the drop down select list. I want the select menu to be set to newly created object. How do I set the selected element with jQuery?

Upvotes: 0

Views: 210

Answers (3)

BraedenP
BraedenP

Reputation: 7215

Once you have your element selected, simply set the option's 'selected' property to true. Example:

Where your select element has id="foo" and the element in the list you want to be selected is element:

$("#foo").element.selected = true;

That's pretty much it.

Upvotes: 1

mattsven
mattsven

Reputation: 23253

$("#mySelect > #idOfTheOptionIWant").attr("selected", "selected");

The reverse being (to deselect an option):

$("#mySelect > #idOfTheOptionIWant").removeAttr("selected");

Upvotes: 3

Adam Bergmark
Adam Bergmark

Reputation: 7536

Set newOption.selected = true.

Upvotes: 0

Related Questions