user15307601
user15307601

Reputation:

How do I set input list dropdown dynamically using JavaScript?

I've seen this question, but it's pretty old, lots of things have changed.

I want to be able to create a virtual data list in my JS code and somehow link that to the #countryInput so those countries get displayed as a dropdown. I don't want to generate HTML for this simple thing.

And if it's impossible or anything like that, is there any better way of doing this ? Cuz it gets messy when you deal with linked data lists and so on.

Run this.

Instead that hard coded example, how do I create this dropdown list without actually generating messy HTML for each country? What if there is 100 countries, the HTML file gets bigger and bigger, and say every country has 10 cities ...

// These countries need to be displayed as a dropdown in the input field
const countries = ["Canada", "Russia", "Germany", "Italy"];

// This is that input field
const countryInput = document.getElementById('countryInput');
<input type="text" list="countriesDataList" id="countryInput" />

<!-- Hard coded  -->
<datalist id="countriesDataList">
    <option>Canada</option>
    <option>Russia</option>
    <option>Germany</option>
    <option>Italy</option>
</datalist> 

Upvotes: 0

Views: 4711

Answers (2)

mplungjan
mplungjan

Reputation: 178026

Like this

You can ajax the list of cities whenever the list changes

// These countries need to be displayed as a dropdown in the input field
const countries = ["Canada", "Russia", "Germany", "Italy"];

// This is that input field
const countryInput = document.getElementById('countryInput');
document.getElementById('countriesDataList').innerHTML = countries
  .map(country => `<option>${country}</option>`).join("");
<input type="text" list="countriesDataList" id="countryInput" />

<!-- Hard coded  -->
<datalist id="countriesDataList">

</datalist>

Upvotes: 1

Wais Kamal
Wais Kamal

Reputation: 6180

You can create a function that dynamically populates your <datalist>. All you need to do then is call that function when your countries array is ready:

// These countries need to be displayed as a dropdown in the input field
const countries = ["Canada", "Russia", "Germany", "Italy"];

// This is that input field
const countryInput = document.getElementById('countryInput');

// This is the datalist
const datalist = document.getElementById('countriesDataList');

function populateList(arr) {
  arr.forEach(country => {
    var option = document.createElement("option");
    option.innerHTML = country;
    datalist.appendChild(option);
  });
}

populateList(countries);
<input type="text" list="countriesDataList" id="countryInput" />

<datalist id="countriesDataList"></datalist>

Whenever your countries array changes, just call populateList again.

Upvotes: 1

Related Questions