styler styler - 11 months ago 54
Javascript Question

how to return the data attribute of an option element in select?

Im trying to log out the data attribute i've attached to each option in my select box but with no success, am I correct using .on('change'... or what should I be doing to achieve this?


$('select').children().on('change', function(e){
console.log( $(this).data('id') );


<option value="1" data-id="option1">wgwg</option>
<option value="1" data-id="option2">wgwerg</option>
<option value="1" data-id="option3">wgwg</option>
<option value="1" data-id="option4">wgr</option>

Answer Source

A change event on option doesn't really make sense as the option is not changing. The event should be on the select.

$('select').on('change', function(e){ 
    console.log( $(this).find("option:selected").data('id') );