Home > database >  Why don't the buttons inside of my $(document).ready(function () call work when clicked?
Why don't the buttons inside of my $(document).ready(function () call work when clicked?

Time:11-02

I have a web page that loads up a table of data. That table is loaded and displayed successfully along with the buttons, however, when I click on button1 or button2, they don't display the alerts and they don't even trip breakpoints that I try to set on the lines. Am I doing this right and my problem is elsewhere or am I just dumb and don't know how to set this up properly?

Thanks!

$(document).ready(function () {
    console.log("page is ready");

    initTable();

    $('#button1').click(function () {
        alert("Button 1 clicked!");
    });

    $('#button2').click(function () {
        alert("Button 2 clicked!");
    });

});

Attempted setting numerous breakpoints to show the buttons are functional but none are triggered upon clicking the appropriate buttons. Expected alerts to show the content set in the strings. I have checked all of the button ids and they are accurate and the function buttons DO work when the function call is coded directly into the html.

CodePudding user response:

Consider the following.

$(function () {
    console.log("page is ready");
    initTable();
    $('table').on("click", "#button1", function () {
        alert("Button 1 clicked!");
    }).on("click", "#button2", function () {
        alert("Button 2 clicked!");
    });
});

You may also consider using Classes instead.

$(function () {
    console.log("page is ready");
    initTable();
    $('table').on("click", ".remove", function () {
      if(confirm("Are you sure you want to Remove this row?")){
        $(this).closest("tr").remove();
      }
    });
});

This function would be executed for each button.remove in the table.

Delegated event handlers have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated event handlers to avoid the need to frequently attach and remove event handlers.

See More: https://api.jquery.com/on/#on-events-selector-data-handler

  • Related