frenchie
frenchie

Reputation: 51927

add elements to select html tag with jquery at runtime

I have a select tag that looks like that:

<select name="MySelect"></select>

At runtime, I have a javascript function that composes some HTML and returns a string that looks like this:

TheOptions = <option>Option 1</option><option>Option 2</option><option>Option 3</option>

I want to add these to the select tag and so far I have:

$('#MySelect').html(TheOptions);

However, when the code executes, it doesn't load the options in the selector. Any suggestions would be helpful.

Thanks.

Upvotes: 0

Views: 3888

Answers (3)

RSG
RSG

Reputation: 7123

You simply need to change name to id.

http://jsfiddle.net/3pWLc/1/

Upvotes: 1

joe_coolish
joe_coolish

Reputation: 7259

What is the best way to add options to a select from an array with jQuery?

That has a really good answer for how to do this.

But the $("#Blah) refers to the id attribute, not the name. So adding the id attr to the <select/> will fix it

Upvotes: 0

David Thomas
David Thomas

Reputation: 253308

Your select element

<select name="MySelect"></select>

Isn't selected by the jQuery selector:

$('#MySelect').html(TheOptions);

The use of the #MySelect is an id based selector, whereas your select has only a name attribute; so instead, you could use:

$('input[name="MySelect"]').html(TheOptions);

Although I'd be more tempted to suggest that you use, instead:

$(TheOptions).appendTo($('input[name="MySelect"]'));

Reference:

Upvotes: 4

Related Questions