Submitting a form with datalist

<label for="homeworld">Your home planet</label>
<input type="text" name="homeworld" id="homeworld" list="planets">
<datalist id="planets">
<option value="Mercury">
<option value="Venus">
<option value="Earth">
<option value="Mars">
<option value="Jupiter">
<option value="Saturn">
<option value="Uranus">
<option value="Neptune">
  • Every time the input is updated in any way, check the current character count against the last character count.
  • If the difference is greater than one, something interesting happened! Maybe the user pasted a value in …or maybe they used the datalist.
  • Loop through each of the options in the datalist.
  • If there’s an exact match with the current value of the input element, chances are the user chose that option from the datalist.
  • So submit the form!
document.querySelectorAll('input[list]').forEach( function (formfield) {
var datalist = document.getElementById(formfield.getAttribute('list'));
var lastlength = formfield.value.length;
var checkInputValue = function (inputValue) {
if (inputValue.length - lastlength > 1) {
datalist.querySelectorAll('option').forEach( function (item) {
if (item.value === inputValue) {
lastlength = inputValue.length;
formfield.addEventListener('input', function () {
}, false);



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jeremy Keith

Jeremy Keith

A web developer and author living and working in Brighton, England. Everything I post on Medium is a copy — the originals are on my own website,