Adding options to Select dropdown

I would like to add options to a Select dropdown menu via Javascript.

The Select dropdown is called myWidth. The options are in the array myOptions.

I now use the following code which I found on the internet. However, I am sure it can be more compact and readable:

var select = document.getElementById("myWidth");

for(var i = 0; i < myOptions.length; i++) {
var opt = myOptions[i];
var el = document.createElement(“option”);
el.textContent = opt;
el.value = opt;
select.appendChild(el);

No that is pretty much what you need to do. I would advise that you use let where possible though as var makes global variables which is not a good idea in most circumstances.

Did you have a specific problem with this or were you looking to just make it shorter?

2 Likes

Hello

Thanks for the tip on the variable.

It works like this. I just would like to make it shorter.

Kind regards

There is little point making it shorter but you can delete the penultimate line because if no value attribute is included, the value defaults to the text content.

You need a closing brace (curly bracket).

Well I suppose you might spare one line here…

el.textContent = el.value = opt

… however more compact code doesn’t necessarily make your code more readable. ;-)

I’d say use const where possible, otherwise let… no need to use var at all AFAICT.

I would make a few simple changes. Not really needed as the code is good as it is but I like it more that way.

const select = document.getElementById("myWidth");
for(const opt of myOptions)
{
    const el = document.createElement(“option”);
    el.textContent = opt;
    el.value = opt;
    select.appendChild(el);
}