sdfgg45 sdfgg45 - 4 months ago 23
Javascript Question

How to distinguish multiple href with the same class when onclick?

I have multiple buttons (a href links) on a page, that are used to vote a product up or down.

i just made some example code that generates the same link-button structure.

<?php for($i=0;$i<30;$i++){ ?>
<a data-id="<?php echo $i; ?>" href="#" class="vote">
<button class="btn-no btn-vote">Yes</button>
</a>
<?php } ?>


I have this jQuery script that handles the click itself:
when i click on the element I'm able to get the correct id, but then it runs trough the rest of the elements on the page, and counting down.

And in this example it gives me like 30 popups and all the numbers.
I need to just the id of element clicked.

<script>
$('.message').hide();

$('.vote').click(function(e){

e.preventDefault();

var element = this;
var id = $(element).closest('span').data('id');

alert(id);

});
</script>

Answer

  
$('.vote').click(function(e){

  e.preventDefault();

  var element = $(this); 
  var id = $(element).data('id');

  alert(id);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a data-id="1" href="#" class="vote">
    <button class="btn-no btn-vote">Yes</button>
</a><br/>
<a data-id="2" href="#" class="vote">
    <button class="btn-no btn-vote">Yes</button>
</a><br/>
<a data-id="3" href="#" class="vote">
    <button class="btn-no btn-vote">Yes</button>
</a><br/>
<a data-id="4" href="#" class="vote">
    <button class="btn-no btn-vote">Yes</button>
</a><br/>
<a data-id="5" href="#" class="vote">
    <button class="btn-no btn-vote">Yes</button>
</a><br/>
<a data-id="6" href="#" class="vote">
    <button class="btn-no btn-vote">Yes</button>
</a><br/>
<a data-id="7" href="#" class="vote">
    <button class="btn-no btn-vote">Yes</button>
</a>

Your script should be like below. No need of .closest('span') as such data-id attribute is in 'a' tag itself.

<script>
$('.message').hide();

$('.vote').click(function(e){

    e.preventDefault();

    var element = $(this); 
    var id = $(element).data('id');

    alert(id);

});
</script>