Nate Pet
Nate Pet

Reputation: 46322

jQuery select from list

I have the following list:

<select id="id1">
    <option value="">Firstone</option>
    <option value="1">Secondone</option>
    <option value="2">Thirdone</option>
</select>

I did the following to select "Secondone" from the list:

$("#id1").val("1").attr('selected', 'selected');

This didn't seem to select it.

How can I select "Secondone" from the list?

Upvotes: 1

Views: 4153

Answers (2)

Gabe
Gabe

Reputation: 50533

To set the selected value of a list you just need to use the val() function, no need to set the attribute for selected.

Example:

jsFiddle

$('#id1').val('1');

If you're trying to literally get the element that is currently selected, you can do this:

var selectedElement = $("#id1").find(":selected");

Upvotes: 3

HMartch
HMartch

Reputation: 728

I believe this is what you want: $("#id1 option[value='1']").attr('selected', 'selected');

Upvotes: 0

Related Questions