st4ck0v3rfl0w
st4ck0v3rfl0w

Reputation: 6755

Remove LI from UL on click using jQuery

So I have a INPUT TEXT that upon keypress=enter prepends an LI to an UL

The LI contains a LINK that gives the user the option to remove it from the UL

HTML (on page load)

<ul id="conditionList"></ul>

after ther user inputs some conditions, the UL gets populated with LI

<li>condition<a href="#" class="clearitem">x</a></li>

However, in my jQuery

$('#conditionList a.clearitem').click(function(){
$(this).parent().remove();
});

will not work!

Is it because it's not recognizing the new LI's?

Upvotes: 2

Views: 16464

Answers (3)

Sarfraz
Sarfraz

Reputation: 382909

Deprecated since 1.9. use on instead of live.

Use live() instead of click there because your link is generated dynamically:

$('#conditionList a.clearitem').live('click', function(){
  $(this).parent().remove();
});

.live()

Attach a handler to the event for all elements which match the current selector, now or in the future.

Depracate since 1.9. use on instead of live.

Upvotes: 6

twerq
twerq

Reputation: 528

Possibly the LIs are added to the DOM after the click event handler has been declared? If so, you might want to look into using live() instead of bind():

$('#conditionList a.clearitem').live('click', function(){
$(this).parent().remove();
});

Upvotes: 1

g.d.d.c
g.d.d.c

Reputation: 48028

You need to use an event binding that's going to recognize created elements. This should do that:

$('#conditionList a.clearitem').live('click', function () {
  $(this).parent().remove();
});

Upvotes: 2

Related Questions