Fredrik
Fredrik

Reputation: 389

Get value from list of links using the same class

I have a list of links and these links have a unique data-value="1" or data-value="2" or something else and the same class="create_post".

<a href="#" class="create_post" data-value="1">Link 1</a>
<a href="#" class="create_post" data-value="2">Link 2</a>
<a href="#" class="create_post" data-value="3">Link 3</a>

When the link is clicked it fires a JS script.

$('.create_post').click(function(event){
    var com = $('.create_post').data('value');     
});

This works great but the com returs "1" from the first value of the list and not from the link that is clicked.

I have tried $(this).attr('value'); but that does not return anything. I have tried using id="create_post" but with the same result.

How do I get the data-value from the actual link that is clicked?

Upvotes: 1

Views: 326

Answers (3)

user8317956
user8317956

Reputation:

$('.create_post').click(function(event) {
  var com = $(this).data('value');
  alert(com)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<a href="#" class="create_post" data-value="1">Link 1</a>
<a href="#" class="create_post" data-value="2">Link 2</a>
<a href="#" class="create_post" data-value="3">Link 3</a>

We must use this inside the click handler to address the element that raised the event.

Upvotes: 0

Satpal
Satpal

Reputation: 133403

You just need to use this in the event handler.

var com = $(this).data('value'); 

$('.create_post').click(function(event) {
  var com = $(this).data('value');
  console.log(com);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="create_post" data-value="1">Link 1</a>
<a href="#" class="create_post" data-value="2">Link 2</a>
<a href="#" class="create_post" data-value="3">Link 3</a>

Upvotes: 3

Rory McCrossan
Rory McCrossan

Reputation: 337570

You should use this within the click handler to reference the element that raised the event. Your current code is retrieving data() from the collection, and as it can only return one value, it gets the attribute from the first element only.

Try this:

$('.create_post').click(function(event) {
  var com = $(this).data('value');
  console.log(com);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="create_post" data-value="1">Link 1</a>
<a href="#" class="create_post" data-value="2">Link 2</a>
<a href="#" class="create_post" data-value="3">Link 3</a>

Also note that your use of attr() didn't work as it should be attr('data-value'), but it should be noted that using the data() method is better practice where possible.

Upvotes: 4

Related Questions