Reputation: 45
Here it's my html code
<select class="data">
<option value="This is my test code" data-id='123'/>
</select>
Now I want to access a data attribute in jquery here it's my jquery code
$( ".data" ).change(function() {
var Id = $(this).data("id")
alert("id: "+Id);
});
but when I'm tried this one it's give a undefine value. please help me.
Upvotes: 3
Views: 60
Reputation: 849
Try this.
$(document).on('change', '.data', function (){
var id = $(this).find('[value="'+$(this).val()+'"]').data('id');
alert(id);
});
Upvotes: 0
Reputation: 133403
Your select
element doesn't have data
attributes. You need to find the child option
of select
then you can use .data()
Use
var Id = $(this).find('option').data("id");
//For selected option
//var Id = $(this).find('option:selected').data("id");
this
refers to element which invoked the handler, in current scenario it will be select
Upvotes: 0
Reputation: 4637
Use this
$( ".data" ).change(function() {
var Id = $(this).find('option:selected').data("id")
alert("id: "+Id);
});
Upvotes: 3