NIKHIL RANE
NIKHIL RANE

Reputation: 4092

Unable to get value of data attribute using jQuery

Here it's my html code

<select class="changeOption">
 {% for dBoy in dBoyList %}
    <option value="{{dBoy.id}}" data-locid='{{dboy.location.id}}'
 {% endfor %} 
</select>

When i'm select any option from dropdown list it shows undefine

JQuery code

$( ".changeOption" ).change(function() {
    var locId = $(this).data("locid")
    alert("id:  "+locId);
});

Upvotes: 5

Views: 666

Answers (1)

Milind Anantwar
Milind Anantwar

Reputation: 82231

this refers to context of select element. you need to find selected option in it and then get the attribute:

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

Upvotes: 5

Related Questions