Rahul Patil
Rahul Patil

Reputation: 45

data attribute in jquery

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

Answers (3)

Mateusz Mania
Mateusz Mania

Reputation: 849

Try this.

$(document).on('change', '.data', function (){

    var id = $(this).find('[value="'+$(this).val()+'"]').data('id');
    alert(id);
});

JSFiddle

Upvotes: 0

Satpal
Satpal

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

I&#39;m Geeker
I&#39;m Geeker

Reputation: 4637

Use this

$( ".data" ).change(function() {
    var Id =  $(this).find('option:selected').data("id")
    alert("id:  "+Id);
});

Upvotes: 3

Related Questions