Skip to content
Advertisement

jQuery not retruning data-id after the first use of the button

I have a php script that creates a table and each id in the table has an edit button. The edit button looks like this.

<button data-siteid="'.$row->site_sn_id.'" class="btn btn-link p-0 m-0" style="font-size:.7rem" id="editBtn" type="button" >Edit</button>

The number of buttons varies but I am trying to get the data-siteid passed to an ajax call like this.

$("#editBtn").on("click", function(){
        var siteID = $(this).data('siteid');
        $.ajax({
            method: "POST",
            url: "edit-modal.php",
            data: {siteID: siteID}
        })
                .done(function( msg ) {
                    $('#editModal').modal('show');
                    $("#bodyContent").html(msg);
                });
    });

Its working on the first edit button of the table but it does nothing after that first button. It wont even open the modal.

Advertisement

Answer

The reason is because ID should be unique across your HTML page and it looks like you’re defining multiple elements with the same ID.

So, instead, try adding and using a class selector:

<button class="... editBtn" ...

$(".editBtn").on("click", function() {
...
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement