0

Currently trying to dynamically toggle content within an HTML document using JQuery based upon a user click.

I have an HTML document and I have the following JQuery code, which dynamically toggles the contents of the div based upon a users click.:

$(function() {
  $(".uen").on("click", uenSearch);
});

function backButton () {
  $(".search-form, .content-wrapper.back").toggle();
  $(".uen > h3, .uen > p").toggle();
  $(".uen").on("click", uenSearch);
}

function uenSearch () {
  $(".uen > h3, .uen > p").toggle();
  $(".search-form, .content-wrapper.back").toggle();
  $(".uen").off();
  $("#back").on("click", backButton);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Search boxes by UEN & Equipment type -->
<div class="search-box uen">
  <h3>Search by</h3>
  <p>UEN</p>
  <form action="#" method="post" class="search-form">
    <input type="text" placeholder="Enter UEN Number" name="uen_number" 
    required>
    <button type="submit">SEARCH</button>
  </form>
  <div class="content-wrapper back">
    <img src="images/back_arrow-white.svg" alt="back-arrow" width="25">
    <p id="back">Back</p>
  </div>
</div>

However, once the user has clicked on the div the first time and the content is changed, if the user tries to click on the "#back" paragraph the event listener is not triggered to toggle the div's content back to it's original.

Any help in solving this would be much appreciated.

Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48
cbaxter87
  • 13
  • 5

1 Answers1

-1
$(function() {
        $(".uen").on("click", uenSearch);
      });

change it to

$(document).on("click", ".uen", uenSearch);

This post talks about event listners in dynamic elements more: Event binding on dynamically created elements?

Budyn
  • 563
  • 7
  • 21