How to get the change event for a datalist with JavaScript?

Sometimes, we want to get the change event for a datalist with JavaScript.

In this article, we’ll look at how to get the change event for a datalist with JavaScript.

How to get the change event for a datalist with JavaScript?

To get the change event for a datalist with JavaScript, we can listen to the input’s change event.

For instance, we write:

<input list="ice-cream-flavors" id="ice-cream-choice" name="ice-cream-choice" />

<datalist id="ice-cream-flavors">
  <option value="Chocolate">
  <option value="Coconut">
  <option value="Mint">
  <option value="Strawberry">
  <option value="Vanilla">
</datalist>

to add the input with a datalist with the options.

Then we write:

const input = document.querySelector('input')
input.onchange = (e) => {
  console.log(e.target.value)
}

to select the input with querySelector.

And then we set input.onchange to a function that logs the selected value.

As a result, when we select an option, we see the value attribute of the option element selected logged.

Conclusion

To get the change event for a datalist with JavaScript, we can listen to the input’s change event.