I have a text file which I am reading and storing the data in a javascript array, it's a list of cuisines. I want to use the array to fill up a drop down select box. I know how to hard code in the values for the drop down box (using correct me if i'm wrong) but I want to be able to use the array to fill it up instead.
<script type="text/javascript">
var cuisines = ["Chinese","Indian"];
</script>
<select id="CusineList"></select>
I have hard coded an array for simplicity, the "CuisineList" is my drop down box
Use a
for
loop to iterate through your array. For each string, create a newoption
element, assign the string as itsinnerHTML
andvalue
, and then append it to theselect
element.DEMO
UPDATE: Using
createDocumentFragment
andforEach
If you have a very large list of elements that you want to append to a document, it can be non-performant to append each new element individually. The
DocumentFragment
acts as a light weight document object that can be used to collect elements. Once all your elements are ready, you can execute a singleappendChild
operation so that the DOM only updates once, instead ofn
times.DEMO
This is a part from a REST-Service I´ve written recently.
The reason why im posting this is because appendChild() wasn´t working in my case so I decided to put up another possibility that works aswell.