Sebastian
Sebastian

Reputation: 3626

All buttons in list returning same ID

I have several buttons in a row, all with class add-btn. When you click on one, I want to log the id of its encasing span. However, what I'm finding is that all buttons log the span of the first add-btn in the list.

$('.add-btn').click(function()
{
    var shop_name = $('.add-btn').closest('span').attr('id');
    $.ajax
    ({
        type: "POST",
        url: "http://www.domain.com/includes/follow.php",
        data: {id: id, shop_name: shop_name},
        success: function(data)
        {
            console.log(data);
        }
    });
});

follow.php:

$shop_name = $_POST['shop_name'];
var_dump($shop_name);

Upvotes: 0

Views: 56

Answers (1)

Bill Criswell
Bill Criswell

Reputation: 32931

Replace $('.add-btn') inside the click handler with $(this).

$('.add-btn').click(function()
{
    var shop_name = $(this).closest('span').attr('id');
    $.ajax
    ({
        type: "POST",
        url: "http://www.domain.com/includes/follow.php",
        data: {id: id, shop_name: shop_name},
        success: function(data)
        {
            console.log(data);
        }
    });
});

What you're currently doing is getting the first .add-btn id.

Upvotes: 5

Related Questions