Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to dynamically add options to an existing select in vanilla javascript

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 closest thing I could find was Dynamically add input type select with options in Javascript which does the latter and was the only I found that doesn't involve JQuery. Although I did try and use it like so:

daySelect = document.getElementById('daySelect'); daySelect.innerHTML += "<option'>Hello world</option'>"; alert(daySelect.innerHTML) 

After I did this there was no change to the select and the alert gave me

HELLO WORLD</option'> 

I apologize if this is simple but I'm very new at javascript and web programming in general. Thank you for any assistance.

EDIT: So I tried the given suggestions like so.

daySelect = document.getElementById('daySelect'); myOption = document.createElement("option"); myOption.text = "Hello World"; myOption.value = "Hello World"; daySelect.appendChild(myOption); 

This has not changed the select in the page at all. Any idea why? And I did check that the code was being run with an alert.

EDIT: The idea did work, it just turned out that it wasn't displaying a value in the dropdown. I don't know why but I can figure that one out I think.

like image 681
avorum Avatar asked Jul 18 '13 17:07

avorum


2 Answers

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'); 
like image 91
Drew Avatar answered Oct 07 '22 05:10

Drew


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); 
like image 29
intuitivepixel Avatar answered Oct 07 '22 06:10

intuitivepixel