JavaScript convert array to select options

JavaScript has various methods to work on an array. We will talk about how to convert array to select options using JavaScript. Select box is a HTML tag to display select dropdown list data. JavaScript has very easy way to convert array to select options.


Convert array to select options

const ddl = document.getElementById('ddl');

for (let i = 6; i <= 100; i++) {
  ddl.add(new Option(i));
}

// another way could be
for (let i = 6; i <= 100; i++) {
  ddl.add(new Option(i, i, false));
  // new Option(text, value, default selected)
  // where first i denotes text second denotes value and false denotes 
  // whether by default it should be selected or not
}

In the above code we have selected the dropdown by the id. Here we have taken ddlas dropdown id. Then loop through the array we have and add each array item to dropdown list by creating instance of Optionwith the help of new keyword.

A working demo is here:

Conclusion

In this article we learned about how to convert array to select options using JavaScript. Dropdown instance of JavaScript has addmethod to add the optionsin it. We just need to create instance of options and then add.

Leave a Reply

Your email address will not be published. Required fields are marked *