How to add options to select with JavaScript?

Spread the love

Sometimes, we want to add options to select with JavaScript.

In this article, we’ll look at how to add options to select with JavaScript.

How to add options to select with JavaScript?

To add options to select with JavaScript, we can create new option elements and append them to the select element as its child.

For instance, we write

const min = 12;
const max = 100;
const select = document.getElementById("selectElementId");

for (let i = min; i <= max; i++) {
  const opt = document.createElement("option");
  opt.value = i;
  opt.innerHTML = i;
  select.appendChild(opt);
}

to select the select element with getElementById.

Then we create an option element in the for loop with createElement.

Then we set its value attribute by setting the value property.

Next we set its text content by setting the innerHTML property.

Finally, we call select.appendChild with opt to append the option into the select element.

Conclusion

To add options to select with JavaScript, we can create new option elements and append them to the select element as its child.

Leave a Reply

Your email address will not be published. Required fields are marked *