How To Fill A DropDown List From Array Using Javascript
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>
2 comments
commentsDear,
ReplyThanks 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
Hello Sir,
ReplyHow to pass the API response to select box of html form