tags:

views:

3416

answers:

2

I have an unordered list with elements and I want to append an item at the end. Here is the current code:

The initial list:

<ul id="all">
  <li>
    Some text <input type="button" class="remove" value="-" />
  </li>
  <li>
    Some text <input type="button" class="remove" value="-" />
  </li>
</ul>

The code that removes a list item:

$(".remove").click(function() {
  $(this).parent().remove();
});

The code that adds a new list item:

$("#add").click(function() {
  $("#all").append(
    "<li>"
    + "Some text"
    + "<input type=\"button\" class=\"remove\" value=\"-\" />"
    + "</li>"
  );
});

The button to add a new list item:

<input type="button" id="add" value="Add" />

When I click the button, a new list indeed is added to the list, but clicking the remove button doesn't do anything.

How do I make this work?


Bonus: Change "Some text" with "<input type="text" /> <input type="text" />" and you will see that the two newly added input elements will have different distance between them from the initial ones. Why? (NOTE: using Firefox 3.0.5).

+7  A: 

I think what you're after is one of the new jQuery 1.3 features - live events. See http://docs.jquery.com/Events/live.

This works for me:

$(".remove").live("click", function() {
  $(this).parent().remove();
});

Bonus:

I'm also using FF 3.0.5, and I have the same amount of space between the two textboxes. If you mean between the second textbox and the button, then I'd have to agree with eimaj and say whitespace is the cause.

Matthew Maravillas
I had the older version of jQuery. I updated it and this works fine.
pek
+3  A: 

#add adds to the node tree (DOM) but .remove was only applied to all existing elements with class "remove" once (presumably onload). Using live adds the handler to new elements too.

(Bonus: The size/rendering issues are just white space: Add a space like this "Some text " works for me in Ff3.0.5)

eimaj
Thanks for the bonus.. ;)
pek