HTML's datalist element autocompletes. This script is my attempt to get it to autosubmit as well.
// Licensed under a CC0 1.0 Universal (CC0 1.0) Public Domain Dedication | |
// http://creativecommons.org/publicdomain/zero/1.0/ | |
(function (win, doc) { | |
'use strict'; | |
// Cut the mustard | |
if (!doc.querySelectorAll || !doc.querySelectorAll('input[list]') || !win.HTMLDataListElement || !win.addEventListener){ | |
return; | |
} | |
// Loop through each input element with a list attribute | |
doc.querySelectorAll('input[list]').forEach( function (formfield) { | |
// Find the corresponding datalist element | |
var datalist = doc.getElementById(formfield.getAttribute('list')); | |
// Store the character count of the input element's value | |
var lastlength = formfield.value.length; | |
// Run this function when the input element's value is updated | |
var checkInputValue = function (inputValue) { | |
// If the current character count is longer by the last character count by more than one, check the datalist | |
if (inputValue.length - lastlength > 1) { | |
// Loop through each option element in the datalist | |
datalist.querySelectorAll('option').forEach( function (item) { | |
// If the value of the option matches the input's current value, submit the form | |
if (item.value === inputValue) { | |
formfield.form.submit(); | |
} | |
}); | |
} | |
// Update the character count | |
lastlength = inputValue.length; | |
}; | |
// Run that function every time the input element is updated | |
formfield.addEventListener('input', function () { | |
checkInputValue(this.value); | |
}, false); | |
}); | |
}(this, this.document)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
Blog post: Submitting a form with datalist