How to remove a created li by clicking on button with JQuery?

Viewed 162

Right now, my code allows someone to create an li by submitting a movie title and its rating. A remove button also appears at the end of this li. I want this li to be removed once the remove button is clicked on. I understand how to do this with Javascript, however how do you do this with jQuery? The ways I have attempted this are:

$('li button').click( function(e) {
    e.target.closest('.li').remove();
})

$('li').on("click", "button", function() {
    $(this).remove()
})

I know there are other ways in Jquery to remove the li, but what is wrong with the above two methods? is it how I selected the items? My entire HTML and JS are below. Thanks in advance!

$('#movieForm').submit(function(event) {
    event.preventDefault();

    let movieInput = $("#movieTitle").val();
    let ratingInput = $("#rating").val();

    $('#movieList').append("<li>" + movieInput + " " + ratingInput + "<button>Remove</button></li>");
    })

$('li button').click( function(e) {
    e.target.closest('.li').remove();
})
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Movies App!</title>
  <link rel="stylesheet"
        href="https://unpkg.com/bootstrap/dist/css/bootstrap.css">
</head>

<body>
<h1>Movies App!</h1>
  <ul id="movieList">

  </ul>
<form id="movieForm">
  <input id="movieTitle" placeholder="Movie Title">
  <input id="rating" placeholder="Rating">
  <input type="submit" id="submit"></button>
</form>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="MoviesApp.js"></script>
</body>

</html>

1 Answers

Your use of on() is almost correct, there's just two flaws. Firstly the primary selector should be the closest parent element to the target which exists in the DOM when the page loads, in this case the ul. You also need to remove the entire li when the event happens, not the button, so use closest(). Try this:

jQuery($ => {
  $('#movieForm').submit(e => {
    e.preventDefault();
    let movieInput = $("#movieTitle").val();
    let ratingInput = $("#rating").val();
    $('#movieList').append(`<li>${movieInput} ${ratingInput}<button>Remove</button></li>`);
  })

  $('ul').on("click", "li button", e => $(e.target).closest('li').remove());
});
<link rel="stylesheet" href="https://unpkg.com/bootstrap/dist/css/bootstrap.css">
<h1>Movies App!</h1>
<ul id="movieList"></ul>
<form id="movieForm">
  <input id="movieTitle" placeholder="Movie Title">
  <input id="rating" placeholder="Rating">
  <input type="submit" id="submit" />
</form>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>

Note that I used arrow functions and template literals in the above example. Neither are relevant to the issue you had, they're just some syntactic sugar to make the logic more succinct.

Related