I\'d like to add option to a select dynamically using plain javascript. Everything I could find involves JQuery or tries to create the select dynamically as well. The clos
Use the document.createElement function and then add it as a child of your select.
var newOption = document.createElement("option");
newOption.text = 'the options text';
newOption.value = 'some value if you want it';
daySelect.appendChild(newOption);
Try this;
var data = "";
data = "<option value = Some value> Some Option </option>";
options = [];
options.push(data);
select = document.getElementById("drop_down_id");
select.innerHTML = optionsHTML.join('\n');
I guess something like this would do the job.
var option = document.createElement("option");
option.text = "Text";
option.value = "myvalue";
var select = document.getElementById("daySelect");
select.appendChild(option);
This tutorial shows exactly what you need to do: Add options to an HTML select box with javascript
Basically:
daySelect = document.getElementById('daySelect');
daySelect.options[daySelect.options.length] = new Option('Text 1', 'Value1');
The simplest way is:
selectElement.add(new Option('Text', 'value'));
Yes, that simple. And it works even in IE8. And has other optional parameters.
See docs:
.add() also works.
var daySelect = document.getElementById("myDaySelect");
var myOption = document.createElement("option");
myOption.text = "test";
myOption.value = "value";
daySelect.add(option);
W3 School - try