Javascript populate select options from array

How To Fill A DropDown List From Array Using Javascript

Javascript populate 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:

Javascript populate select options from array


Javascript populate select options from array

Javascript populate select options from array

When I first started learning React — I remember struggling to figure out what the necessary logic would be to create a dropdown based on items from an array or object. While it is very straight forward to me now, I'm sure I won't be the last person to have that initial struggle when first building an app with React that needs a dropdown like that. The goal of this post is to help those who may need it in the future.

This post will go over a simple scenario on how to create and dynamically populate dropdown options based on data in an array. This post assumes that you have a general idea of how React works as well as knowledge about React Hooks — specifically useState

The Situation

We have an array which contains some type of data — whether it is hard coded values or values that came from an external source, like an API.

The Goal

We want to take each value in that fruits array and turn it into an option within a dropdown menu. Then display that selected option above the dropdown.

The Starter Code

We have a simple React app / component that has:

  • an array of objects — each representing a fruit — with keys for its value (what we actually want React to use/show us after selecting it) and its label (what we'll see in the dropdown list options).
  • a piece of state — that we'll use to display our selection
  • a handleFruitChange function on the select element so that we can update state after the selection changes
  • the default / starting option in our dropdown

import React, {useState} from 'react';
import './App.css';

function App() {
  // Array of objects containing our fruit data
  let fruits = [
    { label: "Apple", value: "🍎" },
    { label: "Banana", value: "🍌" },
    { label: "Orange", value: "🍊" }
]

// Using state to keep track of what the selected fruit is
let [fruit, setFruit] = useState("⬇️ Select a fruit ⬇️")

// Using this function to update the state of fruit
// whenever a new option is selected from the dropdown
let handleFruitChange = (e) => {
  setFruit(e.target.value)
}

  return (
    <div className="App">
    {/* Displaying the value of fruit */}
    {fruit}
    <br />

    {/* Creating our dropdown and passing it the handleFruitChange 
      so that every time a new choice is selected, our fruit state 
      updates and renders an emoji of the fruit.
    */}
    <select onChange={handleFruitChange}> 
        {/* Creating the default / starting option for our 
          dropdown.
         */}
      <option value="⬇️ Select a fruit ⬇️"> -- Select a fruit -- </option>
    </select>

    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Populating the Dropdown

Now that we have the basic layout of our app and the very beginning of our dropdown — we'll need to go through each object in the fruits array and create an option element for it, with the corresponding value / label.

import React, {useState} from 'react';
import './App.css';

function App() {
  // Array of objects containing our fruit data
  let fruits = [
    { label: "Apple", value: "🍎" },
    { label: "Banana", value: "🍌" },
    { label: "Orange", value: "🍊" }
]

// Using state to keep track of what the selected fruit is
let [fruit, setFruit] = useState("⬇️ Select a fruit ⬇️")

// Using this function to update the state of fruit
// whenever a new option is selected from the dropdown
let handleFruitChange = (e) => {
  setFruit(e.target.value)
}

  return (
    <div className="App">
    {/* Displaying the value of fruit */}
    {fruit}
    <br />

    <select onChange={handleFruitChange}> 
      <option value="⬇️ Select a fruit ⬇️"> -- Select a fruit -- </option>
            {/* Mapping through each fruit object in our fruits array
          and returning an option element with the appropriate attributes / values.
         */}
      {fruits.map((fruit) => <option value={fruit.value}>{fruit.label}</option>)}
    </select>
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Now our dropdown will include an option for each fruit in our fruits array. After selecting one, it'll display above the dropdown.

Note: This code would give you a warning in console because we did not give the option a key (which React wants for list items). To get rid of the warning you'd simply update the code to look like this:

{fruits.map((fruit) => <option key={fruit.label} value={fruit.value}>{fruit.label}</option>)}

Enter fullscreen mode Exit fullscreen mode

And thats that! You can view the live demo of this and explore the code yourself on this Replit.

Feel free to reach out here or on my socials for any questions, suggestions, or to say hello 👋

How do you populate the options of a select element in JavaScript?

To populate select list with jQuery, use for loop along with append() and append the options to the already created select.

How can I give an array as options to select element?

To set a JavaScript array as options for a select element, we can use the options. add method and the Option constructor. to add the select drop down. to select the select element with querySelector .

How do I bind a Dropdownlist in JavaScript?

1. Get my source(datatable) in format "Key1-Value1|Key2-Value2|........" keep it in hiddenfield. 2. Then in javascript parse this string iterate and create Option object and fill dropdown by getting it by ID.

How do you populate a list in JavaScript?

In JavaScript, you can use the Array. fill() method to populate an array with a zero or any other value like an object or a string. This method replaces all elements in an array with the value you want to populate the array with and returns the modified array.