0

I have an ordered list in HTML:

<ol id ="list">
</ol>

which gets added to using JQuery/javascript:

$(function (){
    $("#click-me").click(function (e){
        e.preventDefault();
        i++;

        var list = $("#list");
        var name = $("#colleague-select option:selected").text();
        var remove = "<button type='button' class='remove-me'> X </button>";
        var entry = "<li>" + name + remove+ "</li>";
        entry.id = "entryid" + i;

        list.append(entry);

        return false;
    });
});

What I'm trying to do is to allow a user to remove an entry in the list by clicking its corresponding button "X". This is the code I've come up with, but it's not working:

$(function (){
   $(".remove-me").click(function(e){

       var list = $("#list");
       var entry = e.parent(); //find parent entry of clicked "X" button
       list.remove(entry);  //remove entry from list
   });
});

Any help guys? I am fairly new to JQuery so an explanation of your answer code would be much appreciated. Thanks.

0

3 Answers 3

1

You need to use event delegation for binding events to dynamically added elements.

$(document).on('click', ".remove-me", function(e){
    var entry = $(this).parent(); 
    entry.remove();  //remove entry from list
});
Sign up to request clarification or add additional context in comments.

Comments

0

just remove the parent element

$(function (){
   $(document).on("click", ".remove-me", function(e){
       $(this).parent().remove(); //find parent entry of clicked "X" button
   });
});

Comments

0

A foolproof way is add the event to the button

<button type='button' onclick='removeMe(this);' class='remove-me'> X </button>

and on js

function removeMe(e)
{
   $(e).parent().remove();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.