Home > Software design >  when jquery .html() is used to set inner HTML, .click() event on form button no longer works
when jquery .html() is used to set inner HTML, .click() event on form button no longer works

Time:11-15

I have a html form which contains a button. This button has a .click() event attached within a js file. This was working fine, until I used jquery .html() to substitute my main page content with the form content. The form shows on the page but clicking the button no longer triggers the event. I am wondering why this is? Code below...

html:

<body>
    <div id="mainContent">
        <!-- Visible page content will show here -->
    </div>

    <div id="otherScreens">
        <form id="loginForm">
            <label for="email">Email</label>
            <input type="text" id="email" spellcheck="false">

            <label for="password">Password</label>
            <input type="password" id="password">

            <button type="submit" id="signInBtn">Sign In</button>

            <ul id="signInMessages"></ul>
        </form>
    </div>

css:

#otherScreens {
    display: none;
}

js:

const mainContentArea = $(document).find('#mainContent');
let onPageContent = $(document).find('#loginForm').html();

$(document).ready(function () {
    mainContentArea.html(onPageContent);
});

$('#signInBtn').click(function (event) {
    event.preventDefault();
    console.log("Hello world!");
}

I tested changing the .click() event to target #mainContent and it triggered upon clicking anywhere within the div on the webpage, as expected. So I'm not quite sure what's happening with the form button?

(does not seem to relate to suggested duplicate Q)

CodePudding user response:

Just put your click function in document.ready(function()

Please check below full jQuery code and replace it with your current code:

const mainContentArea = $(document).find('#mainContent');
let onPageContent = $(document).find('#loginForm').html();

$(document).ready(function () {

    mainContentArea.html(onPageContent);
    
    $('#signInBtn').click(function (event) {
    event.preventDefault();
    console.log("Hello world!");
});
});

Thanks.

CodePudding user response:

This is quite logical (and can be explained). You create an object, wire events to that object - then replace that object with a similar object and you expect the events to magically be wired.. That doesn't happen.

Each time you dynamically add (delete, replace, whatever) elements with events bound to that element, you need the DOM to be aware of that event. Even so, you could even end-up having more than one event wired to the same element.

So let's say (as an example).

function replaceElement(htmlContent) {
   $('.mybutton').off('click'); // drop the event handler
   $('#mainContent').html(htmlContent); // replace content
   // add event handler
   $('.mybutton').click(function() { 
      console.log('yup, working again');
   });
}
  • Related