Łukasz Samulnik
Łukasz Samulnik

Reputation: 11

Problems with removing item from list

Can anyone tell me why this is not working corectly?
I want a function that will remove list item when I click on it - instead it is removing the whole list.

$(document).ready(function(){
    $( "#add-tag" ).on("click", function(x) {
        var tag = $("#new-tag").val();

        $("#galleries div:first-child").clone().appendTo("#galleries");

        $("#galleries-list").append('<li>' + tag + ' gallery: <a href="#"> remove</a></li>');
        $("#new-tag").removeAttr("value");
        x.preventDefault();
    });

    $("#galleries-list li a").on("click", function(x) {
        var elem = $(this);
        $(elem).remove();
    });


});

Upvotes: 0

Views: 57

Answers (2)

Twisty
Twisty

Reputation: 30893

Working Example: https://jsfiddle.net/Twisty/88t09ma8/2/

JQuery

$(document).ready(function() {
  $("#add-tag").on("click", function(x) {
    x.preventDefault(); // Keep form from submitting
    var tag = $("#new-tag").val();
    $("#galleries div:first-child").clone().appendTo("#galleries");
    $("#galleries-list").append('<li>' + tag + ' gallery: <a href="#"> remove</a></li>');
  });

  $(document).on("click", "ul#galleries-list li a", function(x) {
    $("#new-tag").val("");
    $(this).parent("li").remove();
    return false;
  });
});

The .on() was not hooking to the dynamically created link, so I had to select it more specifically. Also tag was not defined.

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68393

make it

$("#galleries-list li a").on("click", function(x) {
    var elem = $(this);
    elem.parent().remove(); //since you want to remove the li on click of a
});

it was already a jquery object, you didn't have to make it again.

Upvotes: 3

Related Questions