3

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.

2
  • $(this).find(':selected').data("id") Commented Mar 3, 2015 at 11:55
  • 2
    and options tags should not be self closed. Commented Mar 3, 2015 at 12:00

3 Answers 3

3

Use this

$( ".data" ).change(function() {
    var Id =  $(this).find('option:selected').data("id")
    alert("id:  "+Id);
});
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

Try this.

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

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

JSFiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.