开发者

add elements to select html tag with jquery at runtime

开发者 https://www.devze.com 2023-02-23 03:19 出处:网络
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:

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

0

精彩评论

暂无评论...
验证码 换一张
取 消