Martin Bean
Martin Bean

Reputation: 39389

Programmatically select newly-created option with jQuery?

I’m using jQuery 1.10.3 to dynamically add an <option> to a <select> list. The relavant code looks like this:

option = '<option value="' + response.id + '">' + response.title + '</option>';
select.append(option);

However, I’m having trouble finding out how to dynamically select this newly-created option. I would have thought something like…

select.append(option).attr('selected', 'selected');

…Would work, but it didn’t.

Is this possible and if so, how so?

Upvotes: 0

Views: 368

Answers (3)

Adil Shaikh
Adil Shaikh

Reputation: 44740

Try this - (you were setting attr selected to the select not to the option)

select.append($(option).prop('selected', true));

Upvotes: 0

Joseph Marikle
Joseph Marikle

Reputation: 78520

I think it's because the focus is still on the select. try something like

$(option).appendTo(select).attr('selected', 'selected');

Source

Upvotes: 1

reggaemahn
reggaemahn

Reputation: 6648

Maybe this will help:

option = '<option selected="selected" value="' + response.id + '">' + response.title + '</option>';
select.append(option);

Update: after reading your comment I believe this isn't a multi select list. In that case you'll have to do this before the above code to have only one selected option:

$("select option").each(function(){
   $(this).removeAttr("selected");
});

Upvotes: 0

Related Questions