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>
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();
});
Try this,
Live Demo
$('select').on('change', function(e){
console.log( $('option:selected', this).data('id'));
e.preventDefault();
});
You can it with Vanilla Javascript:
console.log(this.querySelector(':checked').getAttribute('data-id'))
You seem to assign the event to the children of select which is wrong.. You need to assign the event to the select directly..
Also this
does not have the data attribute. It is the option that is selected
.. So change your code to this
Try this
$('select').on('change', function(e){
console.log( $(this).find('option:selected').attr('data-id') );
}).change();
OR
$('select').on('change', function(e){
console.log( $(this).find('option:selected').data('id') );
}).change();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With