styler styler - 1 year ago 62
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?

JS

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


HTML

<select>
<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>
</select>‚Äč

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') ); 
    e.preventDefault(); 
}); 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download