Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding options to an html select element

I have the following select element in my html file:

<select id="usr-slct">
</select>

to which I am trying to add some options using javascript in a script tag just before the end of the document's body. Like this:

var selector = document.getElementById("usr-slct");
var newoption = document.createElement("option").text="User1";
selector.add(newoption);

I would like to know why this code does not make my page display the new option in the select and how can I make it work as intended?

like image 676
Valence Avatar asked Jul 21 '26 17:07

Valence


2 Answers

document.createElement("option").text="User1" returns "User1", the result of the assignment, not a HTMLOptionElement. You should code:

var newoption = document.createElement("option");
newoption.text = "User1";
selector.add(newoption);

edit: OP is using .add() method for adding an option to the select element. HTMLSelectElement object does have .add() method.

like image 174
undefined Avatar answered Jul 24 '26 05:07

undefined


Your select element has an 'options' property, which is an array. You can create new options by using:

selector.options[selector.options.length] = new Option('text1', 'value1');

This would add a new Option, with text of text1 and value of value1, to the end of the selector's options array which would return the result you are looking for.

like image 27
Richard Kho Avatar answered Jul 24 '26 07:07

Richard Kho