18

I have a list of entries generated by PHP, each in their own div and each with a unique ID. I'm trying to develop an AJAX call that can remove each entry based on their ID, however whenever I run the script below, it always returns 0.

<div>
    Some entry here
    <button id="0" class="remove">Remove</button>
</div>
<div>
    Another entry here
    <button id="1" class="remove">Remove</button>
</div>
// ... and so on

<script>
    $(".remove").click(function() {
        var id = $(".remove").attr('id');
        alert(id); // debug
        // AJAX call here
    });
</script>

Previously I tried the same thing except the other way around - the id returned by PHP was in the class attribute and the id attribute had the value 'remove' and this only returned 0 for the first button. The second button didn't invoke the jQuery script at all.

How can I pass a unique ID to the same jQuery call?

SteppingHat
  • 1,078
  • 2
  • 20
  • 43

5 Answers5

17

Try this

$(".remove").click(function() {
    var id = $(this).attr('id'); // $(this) refers to button that was clicked
    alert(id);
});
Oleksandr T.
  • 69,412
  • 16
  • 152
  • 136
9

The vanilla option for future viewers.

  1. Select all elements with class remove
  2. Iterate through the elements, assigning a click handler
  3. On click remove the parent element
  4. Log the id to the console

(function () {
    "use strict";
    var buttons = document.getElementsByClassName('remove');
    for ( var i in Object.keys( buttons ) ) {
        buttons[i].onclick = function() {
            this.parentElement.remove();
            console.log(this.id);
        };
    }
})();
<div>Some entry here
    <button id="0" class="remove">Remove</button>
</div>
<div>Another entry here
    <button id="1" class="remove">Remove</button>
</div>
6

Just use this.id to get id of the element

$(".remove").click(function() {
  alert(this.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  Some entry here
  <button id="0" class="remove">Remove</button>
</div>
<div>
  Another entry here
  <button id="1" class="remove">Remove</button>
</div>
Pranav C Balan
  • 106,305
  • 21
  • 136
  • 157
3
$(".remove").on("click",function() {
    var id = $(this).attr('id');
    console.log(id);
});
Amit Soni
  • 1,402
  • 1
  • 9
  • 15
3

You need to use the this keyword to refer to the clicked element:

$('.remove').click(function() {
    var id = this.id;
    // OR
    var id = $(this).attr('id');
});
Jake Opena
  • 1,357
  • 1
  • 10
  • 18