简体   繁体   中英

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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM