The <datalist>
element is super useful for autocomplete-like functionality, but there's no native way to automatically submit a form when an option is selected. Jeremy has come up with a neat logic flow that can enhance the element to do just that:
- Store the input element's character count and keep it updated;
- Each time an update occurs, compare the new count to the previous value;
- If the new count is greater than the previous one by > 1 it means the user has either pasted in additional characters or has selected something from the datalist, so compare the string to the datalist options;
- If there is a match, submit the form.
There are some issues. Jeremy points out that a selection that is only one character different won't trigger the autosubmit, which seems fair. I can also see potential issues with substring matching that could occur in certain situations. But as he says, it's a great enhancement to native functionality that provides plenty of fallbacks if needed.
He also provides a rough outline of his code, plus there's a Gist if useful:
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) { formfield.form.submit(); } }); } lastlength = inputValue.length; }; formfield.addEventListener('input', function () { checkInputValue(this.value); }, false); });