标签云

微信群

扫码加入我们

WeChat QR Code

I have to get the selected option's id.This way returns always the first id, it returns "1" :function myFunction() {var skills = document.getElementById('toto');var skillId = skills.getAttribute('data-id');console.log(skillId);}<label>Skills :<input id="inputTest" name='skill' list='skills'><datalist id='skills'><select><option id="toto" data-id="1">HTML</option> <option id="toto" data-id="2">Jquery</option> <option id="toto" data-id="3">CSS</option></select></datalist></label><button type="button" id="button1" onclick="myFunction()"> Clickhere </button>This way doesnt works , it returns "null" :<label>Skills :<input id="inputTest" name='skill' list='skills'><datalist id='skills'><select> <div id="toto"><option data-id="1">HTML</option><option data-id="2">Jquery</option><option data-id="3">CSS</option> </div></select></datalist></label><button type="button" id="button1" onclick="myFunction()"> Clickhere </button><script>function myFunction(){var skills = document.getElementById('toto');var skillId = skills.getAttribute('data-id');console.log(skillId); }</script>The following way doesnt works too : ...<datalist id='skills'>...<script>function myFunction(){var skills = document.getElementById('skills');var skillId = skills.getAttribute('data-id');console.log(skillId); }</script>And If i put the id on the, it doesnt works too..the getAttribute() method is inevitably in the same <div></div> that getElementById() method ?I just want to understand the correct functioning..There he another way to do that without datalist ? Because "the datalist tag is not supported in Internet Explorer 9 and earlier versions, or in Safari".Thanks a lot :)


Unfortunately, your code always return the first id : "1"

2019年10月18日23分16秒

SimonDelaunay, updated the answer....please check:)

2019年10月18日23分16秒

it works great Mamun, thanks a lot. It seems to be a little bit complex. There must be a simpler way to answer this question, no ?

2019年10月18日23分16秒

That's really cool...+1

2019年10月18日23分16秒