Javascript – jQuery using multiple buttons of the same class to return a value


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.

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

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

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?

Best Solution

Try this

$(".remove").click(function() {
    var id = $(this).attr('id'); // $(this) refers to button that was clicked