Muhammad Umar
Muhammad Umar

Reputation: 237

how to get data attribute value from link tag?

I am using some Html and jQuery code. I want to get data-name value from link tag. Below is my link code that I am using:

<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(){
    $(this).click(function(){

    console.log($(this).data("name"));
    });

});
</script>
<a class="dz-cover" href="javascript:undefined;" data-name="cover" data-dz-remove="">Make Cover</a>

When i click on link tag my jquery code is below console.log($(this).data("name")); but it giving me undefined what i do where i am wrong please help me

Upvotes: 0

Views: 1585

Answers (2)

mplungjan
mplungjan

Reputation: 177691

  1. You need to wrap in a click event
  2. You need to cancel that click event too
  3. Please get rid of the ugly JavaScript href now you cancel the click

Like this

$(function(){
  $(".dz-cover").on("click",function(e){
    e.preventDefault(); 
    console.log($(this).data("name"));
  });
});

Using

<a class="dz-cover" href="plsenablejs.html" data-name="cover" data-dz-remove="">Make Cover</a>

Upvotes: 1

abhi
abhi

Reputation: 1084

try the below code

<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(){
  $(".dz-cover").click(function(){
    console.log($(this).attr("data-name"));
  });
});
</script>

Upvotes: 0

Related Questions