Languages
[Edit]
EN

JavaScript - fill select element dropdown list with array

0 points
Created by:
Iona
445

In this article, we would like to show you how to fill a select element dropdown list with an array using JavaScript.

Practical example

In this example, we create a select element with the first option only. Then inside a simple for loop we dynamically create more option elements whose value and textContent properties are taken from the numbers array.

// ONLINE-RUNNER:browser;

<html>
<body>
  <form>
    <select id="selectNumber">
      <option>Select number</option>
    </select>
  </form>
  <script>

    var select = document.querySelector('#selectNumber');
    
    var numbers = [1, 2, 3];
    
    for (var i = 0; i < numbers.length; ++i) {
        var option = numbers[i];
        var element = document.createElement('option'); // creates option element
        element.textContent = option;                   // sets option text
        element.value = option;                         // sets option value
        select.appendChild(element);                    // appends option element inside select
    }

  </script>
</body>
</html>

 

References

  1. Node.appendChild() - Web APIs | MDN
  2. Document.querySelector() - Web APIs | MDN
  3. Document.createElement() - Web APIs | MDN

Alternative titles

  1. JavaScript - populate drop down list with array
  2. JavaScript - populate dropdown list with array
  3. JavaScript - fill HTML select options list with array
  4. JavaScript - fill HTML combo box list with array
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join