Explain Codes LogoExplain Codes Logo

Html combo box with option to type an entry

javascript
autocomplete
input-field
user-experience
Nikita BarsukovbyNikita Barsukov·Jan 11, 2025
TLDR

For a combo box that allows predefined selection and custom text entry, use an <input> with the list attribute and link it to a <datalist> element:

<input list="fruits" name="fruit"> <datalist id="fruits"> <option value="Apple"> <option value="Banana"> <option value="Cherry"> <!-- Add more options as needed --> </datalist>

Simple and efficient, this provides a combo box containing the options Apple, Banana, Cherry, etc., while also offering users the flexibility to type their own entry.

Improve experience with JavaScript

Auto-select suggestions on type

A nifty way to improve your user's interaction is through JavaScript. By implementing a simple script, your input box can auto-select an entry as it's being typed. This streamlines the process and helps avoid unnecessary key pressing.

// Makes typing more fruitful! document.querySelector('input[list="fruits"]').addEventListener('input', function(e) { var inputVal = this.value; var listOptions = document.querySelectorAll('#fruits option'); for(var i = 0; i < listOptions.length; i++) { if(listOptions[i].value === inputVal) { // Finally, we have a match! this.value = listOptions[i].value; break; } } });

Providing a fallback mechanism

Remember that although <datalist> is widely supported in most modern browsers, it's essential to provide a fallback mechanism when catering to older browser versions. A good strategy is implementing an <input> and <select> combo, using JavaScript to synchronize their values.

Styling your combo box

With CSS you can style your combo box according to your aesthetic taste, from dimensions to fonts and colours:

// The apple of my combo box style input[list="fruits"] { width: 200px; padding: 5px; border: 1px solid #ccc; }

Advanced box with libraries

For more complex cases, consider using libraries like jQuery UI's Autocomplete, which adds sophisticated functionality like custom rendering of list items, callback features and remote data sourcing.

Possible pitfalls & solutions

  • Lack of user input option: Always allow free typing to not restrict the user's choices.
  • Inaccessible resources: Archives like Archive.org may be useful, but always verify the content's validity.
  • Recycled code: Ensure any examples or repositories (like the ones on GitHub or dojo) you use as reference are up-to-date.