0

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.

frenchie
  • 51,731
  • 109
  • 304
  • 510

3 Answers3

4

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:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
1

You simply need to change name to id.

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

RSG
  • 7,013
  • 6
  • 36
  • 51
  • If he *changes* the `name` to `id` then how will he retrieve the submitted values? (I'm assuming a submission to a server-side script, obviously). – David Thomas Apr 06 '11 at 22:37
  • 1
    Perfectly valid point- of course you could add a separate name or change the selector. FWIW I upvoted your answer for completeness before I submitted mine- I'd already made the jsfiddle so I posted anyway. We can continue the shameless race for JQuery reputation points in five minutes if he's not able to figure it out and posts again. – RSG Apr 06 '11 at 23:12
  • 1
    That's one of the few times I've ever, literally, laughed at a comment, thank you for that =) my own shameless race is, however, finished until tomorrow evening. +1, and the best of luck to you in the interminable pursuit of jQuery rep! =D – David Thomas Apr 06 '11 at 23:22
0

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

Community
  • 1
  • 1
joe_coolish
  • 7,201
  • 13
  • 64
  • 111