0

I am trying to create a simple list with the option to add and remove elements, but it seems there are some scope rules about the selectors that I couldn't find in the official documentation. My HTML, including the jQuery is as follows:

$(function() {
  $("#add").click(function() {
    let val = $("input").val();
    if (val !== "") {
      let ele = $("<li></li>").text(val);
      ele.append("<button class='rem'>X</button>");
      $("#mylist").append(ele);
      $("input").val("");
      // $(".rem").click(function(){
      //   $(this).parent().remove();
      // });
    };
  });
  $(".rem").click(function() {
    $(this).parent().remove();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="Add new item">
<button id="add">Add</button>
<ol id="mylist">

</ol>

The commented part is the part that is running properly, but the one that is outside of the click function for the #add element is not working.

AuxTaco
  • 4,883
  • 1
  • 12
  • 27

1 Answers1

1

When you call $(".rem").click(.. jQuery will look for elements with class ".rem" and bind this new click event.

However, this only happens once. If you add elements later with the same class, those don't automatically get that event.

So what you'll want to do is bind this event to the new element you created, after you created it.

Lets clean this up:

<script>

function onAddClick() {
    let val = $("input").val();
    if (val !== ""){
      let ele = $("<li></li>").text(val);

      ele.click(onRemClick); <--- HERE 

      ele.append("<button class='rem'>X</button>");
      $("#mylist").append(ele);
      $("input").val("");
    };        
}
function onRemClick() {
   $(this).parent().remove();
}

$(function() {
  $("#add").click(onAddClick);
});
</script>
Evert
  • 93,428
  • 18
  • 118
  • 189