Skip to content

Instantly share code, notes, and snippets.

Last active May 28, 2022 16:09
What would you like to do?
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
(function (win, doc) {
'use strict';
// Cut the mustard
if (!doc.querySelectorAll || !doc.querySelectorAll('input[list]') || !win.HTMLDataListElement || !win.addEventListener){
// 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) {
// Update the character count
lastlength = inputValue.length;
// Run that function every time the input element is updated
formfield.addEventListener('input', function () {
}, false);
}(this, this.document));
Copy link

adactio commented Sep 30, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment