-2

A simple click event is not firing on my list items with the following line of code:

$("ol > li").on("click", listItemClickEventHandler);

To break down the problem, I cached the reference to the query selector first and then called the on function on it.

The query selector does return an object but I can't tell if that's the right object to set the handler on except for the fact that I've done this a million times in the past and it has worked.

function showAllCookies() {
  $("ol").empty();
  let all = []; //getAllCookies();
  if (all) {
    for(let cookie of all) {
      $("ol").append(`<li>${cookie}</li>`);
    }
  } else {
    $("ol").append(`There are no cookies to display.`);
  }
}

$(btnSave).on("click", function(event) {
 // create cookie
});

$("input[type='text']").on("keyup", function(event) {
  // trigger save
});

$("ol > li").on("click", listItemClickEventHandler);

function listItemClickEventHandler(event) {
  let key = event.target.id;
  $("#txtCookieName").val(key);
  // to do
  $("#txtCookieValue").val("");
}

showAllCookies();
.header {
  font-size: 1.4rem;
  font-weight: bold;
}
input[type="text"] {
  width: 200px;
  margin: 10px;
}
#errorMessage {
  color: red;
}
li:hover {
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.js"></script>
<div>
  <div class = "header">All Cookies</div>
  <ol>
  </ol>
</div>

<div>
  <div class = "header">Enter a key and value to create a new cookie or to update an existing one</div>

  <div id = "errorMessage"></div>
  <input type = "text" id = "txtCookieName" value = "" placeholder="cookie name"/><br />
  <input type = "text" id = "txtCookieValue" value = "" placeholder="cookie value"/>
  <button id = "btnSave">Save</button>
</div>
vzwick
  • 10,424
  • 5
  • 39
  • 60
Water Cooler v2
  • 29,006
  • 41
  • 139
  • 286
  • 1
    Please read [Something on my web site doesn't work. Can I just paste a link to it?](http://meta.stackoverflow.com/questions/125997/something-on-my-web-site-doesnt-work-can-i-just-paste-a-link-to-it). Questions that depend on external resources to be understood become useless when the external resource goes away or is fixed. Create a [MCVE] and put it in **the question itself** instead. – Quentin Apr 23 '19 at 12:27
  • What error(s) do you get in your console? – j08691 Apr 23 '19 at 12:28

1 Answers1

1

No <li>s exist below the <ol> at the time of your event binding.

Since you're adding <li>s dynamically, you probably want to bind the event handler to the <ol> and use event delegation to capture events bubbling up from the dynamically added <li>s:

$('ol').on('click', 'li', listItemClickEventHandler);
vzwick
  • 10,424
  • 5
  • 39
  • 60