html - JavaScript returning NULL/Undefined when trying to get a data attribute -
i have been trying values stored inside data attribute called data-title, javascript doesn't display value have stored inside it. been trying put value inside alert testing, doesn't work. following piece of code. thank you.
<select id='item_id' onchange='changevalue();'> <option data-title="title 1">1</option> <option data-title="title 2">2</option> <option data-title="title 3">3</option> <option data-title="title 4">4</option> </select> <script type="text/javascript"> function changevalue(){ var option=document.getelementbyid('item_id'); alert(option.getattribute('data-title')); } </script>
to retrieve data-title value currently-selected option, select element lacking attribute:
function changevalue(){ var select = document.getelementbyid('item_id'), option = select.getelementsbytagname('option')[select.selectedindex]; alert(option.getattribute('data-title')); }
Comments
Post a Comment