Show datalist labels but submit the actual value
To show user-friendly labels while submitting actual values, use label
for display, and value
for the data to be submitted within <option>
tags in a <datalist>
. The label appears in the UI; the value goes on form submission.
Choosing "Widget A" or "Widget B" delivers "12345" or "67890", respectively.
Detailed breakdown
Leveraging JavaScript for value assignment
Ever wondered how to take the user's selection and use it to get the real value, the one that's meant to be submitted? The answer is JavaScript. Simply update a hidden input field value to match the data-value
of the selected option.
And some JavaScript magic:
Your programming language, your choice: JavaScript vs jQuery
Both plain JavaScript and jQuery can handle this job. Here's how:
Just imagine jQuery selectors as friendly elves fetching the option values in a flash. .data()
method? Just a magic spell for handling data attributes.
Non-unique labels? Interesting challenge...
When labels are not unique, but you still want to submit the correct value, JavaScript can help! It'll parse and match the user input to the right entry within the <datalist>
.
Universal experience
Finish-line in sight: Cross-browser support
Always remember to test your implementation in various browsers. Whether it's Chrome happily gobbling up your code or Firefox spitting out errors, or Opera singing praises of your solution, or Internet Explorer... well, being Internet Explorer.
Not all browsers are friends of datalist: The fallback plan
When browsers get picky and don't fully support <datalist>
, have a graceful fallback in line. Using a <select>
element with a search function can duplicate a datalist experience:
Pro tips for beginners
User interaction: Let's jazz up!
Improve user experience by triggering the list of values when the field gains focus:
Was this article helpful?