Jessica Mather Jessica Mather - 5 months ago 10
jQuery Question

How to dynamically delete an item from a dynamically created list?

How do I delete from my dynamically created list?

This is a sample of what I want:
https://jsfiddle.net/jessica_mather123/8vgu5bqk/8/

How the list is created:

$('#button').click(function() {
var value = $("#id :selected").text();
var value1 = $("#id :selected").text();
var value2 = $("#id").val();
$("#ul").after('<li style="display:list-item; padding:5px;border:2px solid black" name="name[]"><strong>attribute 1:</strong> ' + value + ', <strong>Attribute 2:</strong> ' + value1 + ', <strong>Attribute 3:</strong> ' + value2 + '</li>');


What I used to try and delete from the list:

$('#ul li').on('click',function(e){
$('this').remove();
});


Everything seems to look right from what I've seen, but I still don't know why it is not deleting?

Answer

Try this:

$(document).on('click', '#ul li', function(e){
    $(this).remove();
});

And change

$("#ul").after('<li style="display:list-item; padding:5px;border:2px solid black" name="name[]"><strong>attribute 1:</strong> ' + value + ', <strong>Attribute 2:</strong> ' + value1 + ', <strong>Attribute 3:</strong> ' + value2 + '</li>');

to

$("#ul").append('<li style="display:list-item; padding:5px;border:2px solid black" name="name[]"><strong>attribute 1:</strong> ' + value + ', <strong>Attribute 2:</strong> ' + value1 + ', <strong>Attribute 3:</strong> ' + value2 + '</li>');

jQuery will miss the dynamically created element the way you add event listeners.

Updated Fiddle

Comments