0
votes

I’m using JQuery 1.8. I want to select an option in my select menu by value so I use this statement

$('.countryField').find('option[value="233"]')

however, the problem with the above is if there are multiple options with the same value, all are selected. How do I adjust the above statement so that only one option is selected? Feel free to message me and lecture about how there should not be select menu with multiple options with the same values.

Edit: Here is the console output in response to one of the suggestions given

> $('.countryField').find('option').prop('selected', false)
jQuery.fn.init[255]
> $('.countryField').find('option[value="233"]:first').prop('selected', true)
[<option value=​"233" selected=​"selected">​United States​</option>​]
> $('.countryField').find('option[selected="selected"]')
[<option value=​"233" selected=​"selected">​United States​</option>​, <option selected=​"selected" value=​"233">​United States​</option>​]
3
In response to your edit - You're setting the selected property, then selecting elements with a selected attribute. Updating the value of a property of an object does not change its html element attributes. The answers to set the property are correct, but you're not selecting properly - jsfiddle.net/h9neus61 - Jason P

3 Answers

0
votes

You can use :first selector here which selects the first matched DOM element.

$('.countryField').find('option[value="233"]:first')
0
votes

:eq(0) will used to choose first option having value "233" and it will be get selected.

$('.countryField [value="233"]:eq(0)').prop('selected', true);
0
votes

this can also be done with pure Javascript

document.querySelector(' .countryField option').setAttribute('selected','selected')