0

Im trying to remove a row. But i can't figure it out really. First of all I've got a button that'll add a new row, that works. But I want to give the user the possibility to remove the just added row. The row has an 'div' inside what acts as an deletebutton. But the deletebutton doesn't work?

I'm I missing something?

Greet,

Juki

function addrow() {
$("#container").append("<div id=\"row_added\"><div class=\"deletebutton\" id=\"delbuttonnumber\"></div><div id=\"addedcolor\" class=\"colorcube\"></div></div>");
}

// deleterow the row
$(".deletebutton").click(function() {
    rowclrid = "#" + $(this).parent().attr("id");
    $(rowclrid).remove();
});

2 Answers 2

2

My guess is that you have assigned the click handler before adding the new content, so the handler is not attached to this particular element. You can use .delegate() to listen for events on all elements below a particular parent element, whether or not they already exist:

$('#container').delegate('.deletebutton', 'click', function(){
    $(this).parent().remove();
});

This listens for all click events that happen inside the element #container using a feature of the DOM called event bubbling, then checks to see if they happened on a .deletebutton element, and, if so, calls the handler.

Note also the simplified code inside the handler.

Sign up to request clarification or add additional context in comments.

Comments

1

I think what you need to do is use the live method. This will add the events for any new item that is added to the DOM, not just the ones that exist when you set the click handler.

// deleterow the row
$(".deletebutton").live('click', function() {
    $(this).parent().remove();
});

You also don't need to get the row by getting the ID - it's simpler in the way above.

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.