Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>​
like image 342
styler Avatar asked Oct 11 '12 16:10

styler


4 Answers

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(); 
}); 
like image 79
James Montagne Avatar answered Nov 03 '22 19:11

James Montagne


Try this,

Live Demo

$('select').on('change', function(e){
    console.log( $('option:selected', this).data('id'));
    e.preventDefault();
});
like image 27
Adil Avatar answered Nov 03 '22 20:11

Adil


You can it with Vanilla Javascript:

console.log(this.querySelector(':checked').getAttribute('data-id'))
like image 44
Arthur Ronconi Avatar answered Nov 03 '22 20:11

Arthur Ronconi


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();
like image 38
Sushanth -- Avatar answered Nov 03 '22 20:11

Sushanth --