Naomi Naomi - 10 months ago 36
Javascript Question

Remove one of the added lines on click

I want to only remove the line of the specific .delete that I press. How can I specify that in jQuery. Now it's removing all the p since I've chosen that as the value but I can't figure out how to make it specific for each line of append.


<div id="menu">
<h3>Shopping list</h3>
<div class="line">
<p class="title">Amount</p>
<p class="title">Product</p>
<p class="title">Price</p>
<input class='amountInput' type='number' name='quantity' min='0' max='1000' step='1'>
<input class='productInput' type="text" name="message" value="">
<input class='priceInput' type='number' name='quantity' min='0' max='1000000' step='0.01'>
<button class="food">Add</button>
<div class="messages">
<div class="totalPrice">


$(document).ready(function() {

var totalPrice = 0;

$('.food').click(function() {
var $frm = $(this).parent();
var toAdd = $frm.children(".productInput").val();
var addPrice = $frm.children(".priceInput").val();
var addAmount = $frm.children(".amountInput").val();

var div = $("<div>");
div.append("<p>" + addAmount + "</p>", "<p id='product'> " + toAdd + " </p>", "<p>" + addPrice + "</p>", "<p class='delete'>" + "X" + "</p>");


totalPrice += addAmount * addPrice;

$(".totalPrice").text("Total Price: $" + totalPrice);



$(document).on('click', '.delete', function() {



You should remove the parent div of the all the p, like:

// This is delegated event as the HTML element is added dynamically 
$(document).on('click', '.delete', function() {
    $(this).closest("div").remove(); // .closest will traverse upwards to find the matched element that is div

Note: You need to use event delegation as the HTML elements are added dynamically. Learn more about it here.