Validate "data-value" in a html "datalist"

I am trying to use “datalist” in html instead of “select”. Most because of the ability to search the list.

The problem is that you can enter a non existing value and I search for a way to validate that the data-value not is empty. Like you type in random text not matching existing data.

My current solution allow non existing values.

Something like this:
<input list="jobs" placeholder="Select Job" required=data-value<>"">

This does not work:

      <input list="codes" placeholder="Select Code" required="data-value">
      <datalist id="codes">
        <option data-value="PM">Project Management</option>
        <option data-value="COPY">Copy</option>
      </datalist>

Fiddle: https://jsfiddle.net/brsf14yu/

Is this possible to validate the “data-value” in a simple way?

Clarification please:

Are you trying to compare the user’s input to the contents of the datalist for that element?

Or are you comparing the user’s input to a different list of acceptable answers not included in the datalist?

1 Like

You would need js to do this as explained in this article.

Here’s a codepen with your code and the JS from that page added.

Hope it is what you wanted :slight_smile:

2 Likes

This is almost exactly what I was looking for. Thank you!

One problem is however how I should submit the “key” to the database. I guess I then have to iterate once more to get the keys?

I have played with a solution that save the “key” at the “input level”, which is easier to fetch with “getAttribute”. I do not still know if this works when submitting to the database.

Som thoughts on this and further simplifying this?
It should be nice to have the this.setCustomValidity(msg);, but I cannot figure out how to get this to work using for (var element of inputs) .

I’ve moved the thread to the JS forum as that would be more appropriate for this question :slight_smile:

1 Like

I am trying to handle a traditional key-value using datalists:

  1. Verify and report that only existing values are allowed.
  2. Store the key in a way that is easy to fetch.
  3. Submit the key to the database.

What I found is that datalists NOT are built for traditional “key-values pair”.

I also found that there are many ways to work around this limitation by looping list, find the key and create hidden field etc.

I have got a solution from @PaulOB that works perfect for #1. But I am still struggling how to fetch values and submit the keys to the database. In order to make it easier to fetch I assume that the keys are easier to fetch when stored in at the input level.

Storing the keys in input makes it simpler to verify as I only have to loop through the input elements (not all options)

Am I thinking in a wrong direction?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.