1

I tried to implement checkbox checked event, but seems cannot trigger it to new elements added to the list. Here is the jquery code.

$("#button").click(function() {
    var toAdd = $("input[name=ListItem]").val();

    $("ul").append(
      `<li class="" id=` +
        generateID() +
        `><input name="name" type="checkbox" class="name" />` +
        listName +
        `</li>`
    );
  });

  $('input[type="checkbox"]').click(function() {
    if ($(this).prop("checked") == true) {
      alert("Checkbox is checked.");
    } else if ($(this).prop("checked") == false) {
      alert("Checkbox is unchecked.");
    }
  });

<ol>
<li id="1" class="">
<input name="name" type="checkbox" class="name"> List Name1 
</li>
</ol>

Thank you

Dan
  • 559
  • 4
  • 9
  • 23

1 Answers1

0

Soluations for existing and new elements :

$('body').on('click', 'input[type="checkbox"]', function() {
      if ($(this).prop("checked") == true) {
          alert("Checkbox is checked.");
      } else if ($(this).prop("checked") == false) {
          alert("Checkbox is unchecked.");
      }
});
A. N. SINHA
  • 106
  • 5
  • 1
    code only answers are considered poor quality – Jaromanda X Oct 01 '19 at 08:56
  • Hi @A.N. SINHA, thank you. I have another question, how to retrieve the id in a list as these ids are random numbers? – Dan Oct 01 '19 at 09:44
  • $('li').on('click', function(){ alert($(this).prop('id')); }); – A. N. SINHA Oct 01 '19 at 09:54
  • I got undefined when getting the test var $("body").on("click", 'input[type="checkbox"]', function() { if ($(this).prop("checked") == true) { let test; $("li").on("click", function() { test = $(this).prop("id"); }); console.log(test); } else if ($(this).prop("checked") == false) { //alert("Checkbox is unchecked."); } – Dan Oct 01 '19 at 10:07