Array not working - only the last option is displaying

Hi ther,e

I have the following code:

$('select[name="myselect"').append($('<option>',
{
  value:1, text:'One'   value:2, text:'Two',  value:3, text:'Three',
}
                             
));

I would like to add the above options to a select menu, but it is only adding the third option.

Does anyone know why this is?

Thanks

It looks like you have a missing closing ‘]’ bracket. Are you getting any errors reported in the console?

I’m not getting any errors with this code, but it’s only adding the third to the option list:

$('select[name="myselect"').append($('<option>',
                               
{
value:1, text:'One',   value:2, text:'Two',  value:3, text:'Three'
}     
                               
));

AFAIK, you can’t create multiple elements like that.

1 Like

I’m not sure I see how that is relevant. Could you explain?

the way @toolman is creating elements, is not allowed. you are supposed to pass an object of attributes as second parameter. i was just referring to the documentation.

What was confusing me, was you replying to myself, rather than @toolman.

oh, so sorry!:disappointed:

One way, would be to do something like the following:

var options = [
  { value: 1, text: 'One' },
  { value: 2, text: 'Two' },
  { value: 3, text: 'Three' }
];

var html = options.map(function(option) {
  return $('<option>', option); 
});

$('select[name="myselect"]').append(html);

This loops over the array of objects and create an option element for each one, and then appends the resulting array to the document. You could build up the option elements using strings, but since we’re already using jQuery it’s neater to use that to create the elements.

2 Likes

My guess is the code is essentially doing similar to

value = 1,
text = 'One',
value = 2,
text = 'Two',
value = 3,
text = 'Three'

That is, each subsequent use of the same key name is over-riding previous.

I guess you could try different key names, eg.

value1 = 1,
text1 = 'One',
value2 = 2,
text2 = 'Two',
value3 = 3,
text3 = 'Three'

but I’m fairly sure what you want is to properly nest as fretburner posted instead.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.