javascript - How to get value of a data-id attribute from selected(different id, same name) datalist (html5) option? -
<input type="text" value="" list="department" /> <datalist id="department"> <option data-id="1" value="arthur"></option> <option data-id="2" value="arthur"></option> <option data-id="3" value="king"></option> <option data-id="4" value="gabriel"></option> </datalist>
i need access value of 'data-id' selected datalist option on click of "#button" or event. there situation: same value name, different data-id. want correct id. should do? think u!
accessing these values can done in 2 ways vanilla javascript, , neither conflicts regular attributes. either use
element.dataset[foo]
element.getattribute('data-' + foo)
(this 1 has more legacy support)
where foo
name of data attribute, i.e. "id"
in case
an <input>
, <datalist>
pair not enforce choice made provided <option>
s , hence not offer direct way see option selected, if want use <select>
instead.
however, can find if there <option>
matches selection iterating through them , checking against value. remember there case nothing matches.
an example of how might follows
document.getelementbyid('check').addeventlistener('click', function () { var output = document.getelementbyid('output'), input = document.getelementbyid('foo'), list = document.getelementbyid('bar'), i; (i = 0; < list.options.length; ++i) { if (list.options[i].value === input.value) { output.textcontent = list.options[i].getattribute('data-id'); return; } } output.textcontent = 'no match found'; });
<input id="foo" type="text" value="" list="bar" /> <datalist id="bar"> <option data-id="0" value="fizz"></option> <option data-id="1" value="buzz"></option>> </datalist> <button id="check">check</button> <span id="output">make choice, click check</span>
Comments
Post a Comment