0

I'm working on kind of an autocomplete-like feature, and instead of rendering my own dropdown, I'm trying out < datalist > because I like using native elements for use on different devices, and also it already comes with a UI feature of selecting items using arrows and enter key.

However when it comes to executing JS events it doesn't seem to offer much.

Lets say I have datalist options like this:

<datalist>
  <option value="item_name" data-id="item_id">
  <option value="item_name" data-id="item_id">
  <option value="item_name" data-id="item_id">
  ...
</datalist>

I need to show the item_name in the list, but when an item is picked, I want to execute something that will use the item_id of that item (send an ajax request for example). But there doesn't seem to be a way to access option's attributes from the < input >'s events.

Is there a way to do this, or can you recommend a different type of native element that could do this, but also be able to go through items using arrow keys and select with enter?

Thanks

I tried using change and input events on the < input > field but they don't seem to have data of the selected option field, and the < datalist > element itself doesn't seem to have any JS events.

I was hoping to be able to trigger something like a change event when I pick an < option >, like you do with < select > elements.

1 Answer 1

0

I do not believe that an event such as you want exists; but doing it manually is easy enough.

document.querySelector('#in').addEventListener('input', evt => {
  const val = evt.target.value
  const listId = evt.target.getAttribute('list')
  const escVal = val.replace(/["\\]/g, '\\$&')
  const option = document.querySelector(`#${listId} option[value="${escVal}"]`)
  if (option) {
    const id = option.getAttribute('data-id')
    console.log(`You selected ${id}!`)
  }
})
<datalist id="vals">
  <option value="foo" data-id="1">
  <option value="bar" data-id="2">
  <option value="baz" data-id="3">
  <option value='qu "moo" \ux' data-id="4">
</datalist>
<input list="vals" id="in">

Of course, you could just as well iterate over each option and test manually that value matches, instead of getting clever with attribute selectors (or tweak my primitive escaping mechanism if it proves insufficient to the task of ensuring that no value "breaks out" of the attribute selector syntax).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Looks like it'll do the job. Hopefully there won't be any items with identical values :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.