Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery append and bind

Tags:

jquery

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).

like image 548
pek Avatar asked Feb 16 '26 03:02

pek


1 Answers

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.

like image 165
Matthew Maravillas Avatar answered Feb 19 '26 01:02

Matthew Maravillas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!