Search code examples
javascriptphpjquery

jquery button event on multiple buttons with the same class


I am having trouble with a button.

With php I am setting the name of the button, so it is not known beforehand what the name of the button is. The button however have a class, but there are multiple buttons. When I click on one of the buttons, all buttons fire their event because they all have the same class.

is there a way that I can make it that only one button fire the event? Here is my code:

    <button class="delad" name="<?php print $user; ?>">Delete this ad? </button>

<script>
$(document).ready(function()
{
    count = 0;
    if(count == 0)
    $(".delad").click(function(e)
    {
        e.stopPropagation() 
        v1 =$(this).attr('name');
        sum = {'v1': v1};
        sum = JSON.stringify(sum);

        $.ajax(
                {
                    url: 'del_ad.php',
                     data: 'json='+ sum,
                    success: function(data) 
                    {
                        alert(data)
                    }
                });
                count += 1;

    });

});

</script>

Solution

  • Try the following:

    <button id="dino" class="delad" name="<?php print $user; ?>">Delete this ad? </button>
    <script>
    $(document).ready(function()
    {
    count = 0;
    if(count == 0)
    $("#dino").click(function(e)
    {
        e.stopPropagation() 
        v1 =$(this).attr('name');
        sum = {'v1': v1};
        sum = JSON.stringify(sum);
    
        $.ajax(
                {
                    url: 'del_ad.php',
                     data: 'json='+ sum,
                    success: function(data) 
                    {
                        alert(data)
                    }
                });
                count += 1;
    
        });
    });