Javascript - Populate Select Option From Array

How To Fill A DropDown List From Array Using Javascript

fill select options from array



In This Javascript Tutorial we will See How To Add A Options To Select And Set Attribute To Option From Array Using For Loop In JS And Netbeans Editor .


Project Source Code:

<!DOCTYPE html>
<html>
    <head>
        <title>Add Option From Array</title>
        <meta charset="windows-1252">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>

        <select id="select">
            <option value="default">default</option>
        </select>
        
        <script>
            
            var select = document.getElementById("select"),
                     arr = ["html","css","java","javascript","php","c++","node.js","ASP","JSP","SQL"];
             
             for(var i = 0; i < arr.length; i++)
             {
                 var option = document.createElement("OPTION"),
                     txt = document.createTextNode(arr[i]);
                 option.appendChild(txt);
                 option.setAttribute("value",arr[i]);
                 select.insertBefore(option,select.lastChild);
             }
             
        </script>

    </body>
</html>

OUTPUT:





Share this

Related Posts

Previous
Next Post »

2 comments

comments
5 juin 2018 à 07:19 delete

Dear,
Thanks for your code, it's great. But I want to select the Option where month[i][2] = "1", there can be more than one selected.
How can I do this? Here is my code.

var month = [["1", "January", ""], [["3", "Mars", ""], ["4", "April", ""], ["5", "May", ""], ["2", "February", "1"]]

var select = document.getElementById('select_table');
for (var i=0; i < month.length;++i){
var option = document.createElement("OPTION"),
txt = document.createTextNode(month[i][1]);
option.appendChild(txt);
option.setAttribute("value",month[i][0]);
select.insertBefore(option,select.lastchild);
}

Regards,
Koen

Reply
avatar
12 août 2020 à 06:35 delete

Hello Sir,
How to pass the API response to select box of html form

Reply
avatar