How to Create a Dropdown List with Array Values using JavaScript ?

07-Nov-2020

.

Admin

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..

#JavaScript