Mario
Mario

Reputation: 123

Delete button works on only first row not on the rest of the rows

I have fetched the values(card details) from an array and put them in an html table, I have also added the delete button for deleting the particular card.

I am deleting this through ajax. When i click on the delete button of the first row, it works perfect but when i click on the other delete buttons from 2nd or 3rd row, there is no action.

Please suggest the correct path to sort out this problem.

Thanks in advance

Here is my code

           <tr>
                        <td><?php echo $val['last4'];?></td>
                        <td><?php echo $val['exp_month'];?></td>
                        <td><?php echo $val['exp_year'];?></td>
                        <td><button id = "del">Delete</button></td>
                    </tr>

Ajax part 


<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
    <script>                        
        $('#del').click(function() {
        //var a=document.getElementById("").value;
        var val0 = $('#id').val();
        var val01 = $('#cust').val();

        var fade = document.getElementById("fade");         

        var show = function(){
        fade.style.display = "block";
        }

        show();
        $.ajax({
        type: 'POST',
        url: 'mywebsite.com/deleting.php',
        data: { card_id: val0,cust_id: val01 },
        success: function(response) {
        fade.style.display = "none";
        // alert(response);
         mystring = response.replace(/^\s+|\s+$/g, "");
        $('#result11').html(mystring);

        }
        });
        });
    </script>

Upvotes: 1

Views: 1599

Answers (2)

M. Eriksson
M. Eriksson

Reputation: 13635

You have the same id on your buttons. Id's must be unique within the html document and can not be shared between multiple elements. Read more about the html id attribute

Change the button to use a class instead:

<td><button class="del">Delete</button></td>

Then change your jQuery to bind to that class instead:

$('.del').click(function(e) {
    // Since we're using ajax for this, stop the default behaviour of the button
    e.preventDefault();

    // Get the value from the clicked button
    var val0 = $(this).val();

I also added the event e in the function call, and stopped the default behaviour of the button (which is to submit the form) when it's clicked.

Upvotes: 5

Monzurul Shimul
Monzurul Shimul

Reputation: 8396

You need to give delete buttons a class and bind event on that class not with id. Then on bind function select values from that row elements and then pass them to Ajax.

Upvotes: 1

Related Questions