Sir Rubberduck
Sir Rubberduck

Reputation: 2282

HTML: Is it still not possible to select a data attribute from a datalist?

I've tried multiple approaches to get the selected item's data attributes (data-id, data-key), but nothing seems to work.

A couple of resources mentioned that this is not possible specifically for datalist...

Is there a way to achieve this now, or is it still impossible?

I'd really appreciate a vanilla Javascript way.

document
  .getElementById('input-journal-item-company')
  .addEventListener("change", (e) => {
    console.log(e.target.dataset) // Empty object DOMStringMap {}
    console.log(e.target.dataset.id) // undefined
    console.log(e.target.getAttribute("data-id")) // null
  })
<input type="text" id="input-journal-item-company" list="input-companies">
<datalist id="input-companies">
    <option data-id="1" data-key="001" value="Company 1">Company 1</option>
    <option data-id="2" data-key="002" value="Company 2">Company 2</option>
    <option data-id="3" data-key="003" value="Company 3">Company 3</option>
</datalist>

Upvotes: 0

Views: 755

Answers (2)

Barmar
Barmar

Reputation: 781096

e.target is the input value, not the option that the value came from. You need to search for the corresponding option.

document
  .getElementById('input-journal-item-company')
  .addEventListener("change", (e) => {
    const option = document.querySelector(`#${e.target.list.id} option[value='${e.target.value}']`);
    console.log(option.dataset) // Empty object DOMStringMap {}
    console.log(option.dataset.id) // undefined
    console.log(option.getAttribute("data-id")) // null
  })
<input type="text" id="input-journal-item-company" list="input-companies">
<datalist id="input-companies">
    <option data-id="1" data-key="001" value="Company 1">Company 1</option>
    <option data-id="2" data-key="002" value="Company 2">Company 2</option>
    <option data-id="3" data-key="003" value="Company 3">Company 3</option>
</datalist>

Upvotes: 1

Brad
Brad

Reputation: 163262

Try this for your JavaScript:

document
  .getElementById('input-journal-item-company')
  .addEventListener("change", (e) => {
    const listOption = e.target.list.querySelector('[value="' + e.target.value + '"]');
    console.log(listOption.dataset.id);
    console.log(listOption.dataset.key);
  })

The key here is that we use e.target.list to get the reference to the <datalist> element bound do the input element that's actually changing. From there, we can query its children with querySelector for one that has a value which matches the input element's value.

http://jsfiddle.net/eboc9yzj/

Upvotes: 1

Related Questions