Dj Genexxe Dj Genexxe - 5 months ago 9
Javascript Question

How to get the index of the element by class that is clicked

I have this code:

<button class="remove" value="1" />
<button class="remove" value="2" />
<button class="remove" value="3" />


$(document).on('click', ".remove", function(e) {
alert($(this).index());
});


It is always alerting
0
. If the user clicked the
button
that has a value of
2
, it must alert
1
but in my code it alerts
0
.

Answer

depending on what you want to finally achieve and assuming that:

<button class="remove" value="34" data-myval="a"/>
<button class="remove" value="33" data-myval="b"/>
<button class="remove" value="32" data-myval="c"/>

if you want to get the value of 'value':

$(document).on('click', ".remove", function(e) {
    alert($(this).val());
});

if you want to get the index of what was clicked:

$(document).on('click', ".remove", function(e) {
    alert($(this).index());
});

if you want to get a custom value:

$(document).on('click', ".remove", function(e) {
    alert($(this).data('myval'));
});