Skip to content

Instantly share code, notes, and snippets.

@adactio
Last active July 17, 2023 17:07
Show Gist options
  • Save adactio/2e3ec8cc3cc1c3b7305accb50144bf1b to your computer and use it in GitHub Desktop.
Save adactio/2e3ec8cc3cc1c3b7305accb50144bf1b to your computer and use it in GitHub Desktop.
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));
@adactio
Copy link
Author

adactio commented Sep 30, 2020

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