user10276993
user10276993

Reputation:

How to handle events in dynamic elements?

I want to create a dynamic questionnaire, loading the next question dynamically, but when I load the second question, the event of the button next2 doesn't respond as if there were no event.

I think it's because I load the input with a JavaScript function. What do I have to do to make it work?

$(document).ready(function() {
  var question2 = `
            <form>
               <input type="number" id="age" placeholder="age">
        <input type="submit" id="next2">
            </form>
          `;
  var question3 = `
            <form>
              <input type = "email" id="email" placeholder="email">
               <input type="submit" id="next3">
              </form>
              `;

  $('#next').click(function(e) {
    e.preventDefault();
    console.log(1);
    $(".questions").html(question2);
  });
  $("#next2").click(function(e) {
    e.preventDefault();
    $(".questions").html(question3);
  });
  $("#next3").click(function() {
    alert('Cool');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<div class="questions">
  <form>
    <input type="text" id="name" placeholder="Name">
    <button type="submit" value="Next" id="next">Next</button>
  </form>
</div>

</html>

Upvotes: 0

Views: 70

Answers (2)

Mark Schultheiss
Mark Schultheiss

Reputation: 34168

You only need one event handler for all this, not multiple.

You are inserting the HTML into the element with the class questions with $(".questions").html. Given that you should hook the event handlers to that element with the questions class to be as close to the element as possible (not make it traverse the entire DOM looking for things in the events.

Here I took the CURRENT html and saved it to myApp which I created to hold stuff and not pollute the global namespace; Then I cycle back to it on the last. Odd that you have both button and input type submit but I also handle that. Since these are submit buttons in a form, I added the submit event in case that is how it gets triggered.

$(function() {
  let myApp = {};

  myApp.question2 = ` <form>I am 2
    <input type="number" id="age" placeholder="age">
    <input type="submit" id="next2"  data-nextthing="question3">
  </form>
`;
  myApp.question3 = ` <form>I am 3
   <input type = "email" id="email" placeholder="email">
   <input type="submit" id="next3"  data-nextthing="question1">
 </form>
 `;

  myApp.question1 = $(".questions").html(); // just to store it
  $(".questions")
    .on('click submit', 'form, button[type="submit"], input[type="submit"]', function(event) {
      event.preventDefault()
      let d = $(this).data('nextthing');
      $(event.delegateTarget).html(myApp[d]);
      return false;
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="questions">
  <form>
    <input type="text" id="name" placeholder="Name">
    <button type="submit" value="Next" id="next" data-nextthing="question2">Next</button>
  </form>
</div>

Upvotes: 0

M Ikram Zafar
M Ikram Zafar

Reputation: 150

You should use $(document). It is a function trigger for any click event in the document. Then inside you can use the jquery on("click","#idname",somefunction), where the second argument specifies which specific element to target. In this case every element inside the body.

 $(document).on('click', '#next', function(e) {
    e.preventDefault();
    $(".questions").html(question2);
  });

Upvotes: 1

Related Questions