Submitting a form with datalist | adactio

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:

  1. Store the input element's character count and keep it updated;
  2. Each time an update occurs, compare the new count to the previous value;
  3. 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;
  4. 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);
});

Explore Other Notes

Newer

Your calendrical fallacy is...

A fun list of the all the irritating edge cases that can crop up once you start dealing with dates and timezones. I'm a particular fan of the more obscure information on the Hebrew Calendar, with […]

Older

Famous colleges

Parents can do their children a favor if, from an early age, kids hear them say “famous college” instead of “good college.”Because there’s very little data that shows […]
  • The &lt;datalist&gt; 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 […]
  • Murray Adcock.
Journal permalink

Made By Me, But Made Possible By:

CMS:

Build: Gatsby

Deployment: GitHub

Hosting: Netlify

Connect With Me:

Twitter Twitter

Instagram Instragram

500px 500px

GitHub GitHub

Keep Up To Date:

All Posts RSS feed.

Articles RSS feed.

Journal RSS feed.

Notes RSS feed.