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>Optio开发者_JAVA百科n 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.
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:
- attribute-equals
[attribute="value"]
selector. appendTo()
.
You simply need to change name
to id
.
http://jsfiddle.net/3pWLc/1/
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
精彩评论