0

I'm currently populating an HTML table to display users. I use calls to an API to serve my user data to the table, and Javascript to append the row to the table. The last entry in each row features a delete button, which is supposed to pass user data as a $put to a separate API endpoint to delete the user of the corresponding row:

//Existing adhoc-users table.
var adhocUsersHtml = "<div><table class='table table-striped'><tr><th>Section</th><th>Role</th><th>First Name</th><th>Last Name</th></tr>";
$.each(json.sections, function (index, section) {
    $.each(section.enrollments, function(index, user) {
        if (user.adhocEnrollment == true) {
            adhocUsersHtml += "<tr><td>" + section.sectionTitle + "</td><td>" + user.roleName + "</td><td>" + user.firstName + "</td><td>" + user.lastName + "</td>"
                + "<td><button id='delete' class='btn btn-default' data-style='height: 30px; margin-top: 0;'>Delete</button></td></tr>";
        }
    });
});
adhocUsersHtml += "</table></div>";
return adhocUsersHtml;

What's the best pattern for scoping 'this' with the delete buttons?

Should I put a custom attribute on the button that holds the user id for that row, and then add an onClick to all delete buttons that grabs the id and preforms the $put?

Is it possible to add an onClick function right after declaring HTML before appending it to the DOM with Javascript?

2 Answers 2

1

Put the user id into a data attribute on the delete button and add a single event handler to the table to handle all delete button clicks.

<button class='delete-user-btn' data-id="myUserId">Delete</button>

$("#myTable").on("click", ".delete-user-btn", function() {
  var id = $(this).attr("data-id");
  //delete code goes here
});
Sign up to request clarification or add additional context in comments.

Comments

1

firstly, you are going to have many buttons so attribute id='delete' isn't appropiate

I will put class "delete" instead without userId and register onClick Listener after all buttons rendered and since each row represent a user, i will put id on each row

<tr data-val="{userID}">
    ....
    <td><button class='btn btn-default delete' data-style='height: 30px; margin-top: 0;'>Delete</button></td>
</tr>

<script>$('.delete').on('click', function(e) {
 var tr = $(e.target).closest('tr'),
 id = tr.data('val')
 ... do your code
})</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.