How to Create a Dropdown List with Array Values using JavaScript ?
Nov 07, 2020
Hi Guys,
In this example,I will learn you how to get dropdown list with array values using javascript.you can easy and simply get dropdown list with array values using javascript.
The task is to add elements to the select element from the JavaScript array. We can also get selected value in dropdown list using JavaScript. Here we will populate the dropdown list with an array. Below is the description of populer approaches used in JavaScript.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Populate dropdown list with array values
</title>
</head>
<body style="text-align:center;">
<h1 style="color:#af1bf9;">
NiceSnippets
</h1>
<p id="geeks" style=
"font-size:20px; font-weight:bold">
</p>
<select id="arr"></select>
<br><br>
<button onclick="nsfn();">
click here
</button>
<p id="gfg" style="font-size: 26px;
font-weight: bold;color: green;">
</p>
<script>
var up = document.getElementById('nice');
var down = document.getElementById('snippets');
var select = document.getElementById("arr");
var elmts = ["HTML", "CSS", "JS", "PHP", "Laravel"];
up.innerHTML = "Click on the button to "
+ "perform the operation"+
".<br>Array - [" + elmts + "]";
// Main function
function nsfn() {
for (var i = 0; i < elmts.length; i++) {
var optn = elmts[i];
var el = document.createElement("option");
el.textContent = optn;
el.value = optn;
select.appendChild(el);
}
down.innerHTML = "Elements Added";
}
</script>
</body>
</html>
It will help you..
- How to set Date in setUTCHours() Method in JavaScript?
- How to Date sets UTC milliseconds in Javascript?
- How to Use push(), unshift(),pop() and shift() With Array in Javascript?
- How to Check if a Variable is a Number in Javascript?
- How To Format a Number Using Fixed - Point Notation in Javascript?
- How to Insert an Element into an Array in javaScript?
- How to remove duplicate elements from JavaScript Array?
- How to calculate years, months and days between two dates in javascript?