How to Populate an HTML Datalist with Array Values Using JavaScript?

Estimated read time 1 min read

Here’s an example of populating an HTML datalist with values from an array using JavaScript:

<input list="dataList">
<datalist id="dataList"></datalist>

<script>
  const data = [
    "Apple",
    "Banana",
    "Cherry",
    "Date",
    "Elderberry"
  ];
  
  const datalist = document.querySelector("#dataList");
  
  for (const item of data) {
    const option = document.createElement("option");
    option.value = item;
    datalist.appendChild(option);
  }
</script>

This will generate a dropdown list with options for each item in the data array, allowing users to select from the list when entering data in the input field.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply