Andy
Andy

Reputation: 10830

How to set a selected option in a select element using JQuery?

I have seen many questions about this, but none seems to be working for me. I have been trying to test it on the chrome developer tools, but nothing. This is my select element:

<select id="mySelect">
  <option value="10">Something</option>
  <option value="11">Something2</option>
</select>

Now I am trying to set it like so:

$('#select option[value="11"]').prop("selected", true)

Now I have also tried using the attr method, but also does not work. I should mention this is a simplified example and my list has hundreds of options. The end goal is to set a new selected item and reflect it on the web page.

Upvotes: 0

Views: 40

Answers (2)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

You can do $("#mySelect").val(11). $("#mySelect") will select <select> tag from DOM which has id mySelect and using .val(11) will set the option tag of select as select which has value attribute equal to 11:

$("#mySelect").val(11);

Upvotes: 3

Vasiliy vvscode Vanchuk
Vasiliy vvscode Vanchuk

Reputation: 7169

$('#mySelect').val(11)

try this

Upvotes: 1

Related Questions