How to Dynamically Generate Options for a Select from JSON Data in JavaScript

Tiempo de lectura: 2 minutos

In this example, we’ll see how to dynamically generate options for a select element in HTML using JSON data and JavaScript.

First, let’s display the array of elements we’ll use as an example:

const jsonData = [
  { id: 1, name: "NameDevCodelight1" },
  { id: 2, name: "NameDevCodelight2" },
  { id: 3, name: "NameDevCodelight3" }
];

Next, we’ll create a function called createSelect that will take the JSON data and generate options for a select element in HTML:

function createSelect(json) {
  var select = document.getElementById("idselect");

  for (let i = 0; i < json.length; i++) {
    var option = document.createElement("option");
    option.text = json[i].name;
    option.value = json[i].id;
    select.add(option);
  }
}

Below, you can see the complete code used for the example:

<!DOCTYPE html>
<html>
<head>
  <title>Generate Select from JSON</title>
</head>
<body>
  <select id="idselect">
    <!-- Options will be added here -->
  </select>

  <script>
     const jsonData = [
  { id: 1, name: "NameDevCodelight1" },
  { id: 2, name: "NameDevCodelight2" },
  { id: 3, name: "NameDevCodelight3" }
  ];

    function createSelect(json) {
      var select = document.getElementById("idselect");

      for (let i = 0; i < json.length; i++) {
        var option = document.createElement("option");
        option.text = json[i].name;
        option.value = json[i].id;
        select.add(option);
      }
    }

    // Call the function with the example JSON
    createSelect(jsonData);
  </script>
</body>
</html>

Finally, here’s how our select element looks:

I hope this helps you. Have a great day!

Leave a Comment