tags:

views:

67

answers:

2

After a page is loaded a user can add some text and with every add, I add a little 'x' so the text can be removed. But when I create a click event on the id of the 'x', nothing happens, I can't click on it.

What am I doing wrong?

$('<div>blabla<span id="remove">X</span></div>').insertAfter($("#add"));


$('#remove').click(function(){
 $(this).hide();

});

+4  A: 

When you assign the click event it only adds it to the elements currently in the document, and not future elements that are added. You need to use the live function:

$('#remove').live( 'click', function(){ /* etc */ })

You need jQuery 1.3+ for this to work.

Note: As Jan pointed out in the comments, you can only have one ID per page. You should change "remove" to be a class and use $('.remove') in the code above.

DisgruntledGoat
you can't have multiple elements with the same ID, that is why his code is not working ...
Jan Hančič
Good point; edited.
DisgruntledGoat
+2  A: 

Since you have more than one of this elements, you can't give all of them the same ID. And even if your code would work it would only hide the span and not the DIV.

You should do something like this:

var newElement = $( '<div>blabla<span class="remove">X</span></div>' );
$( 'span.remove', newElement ).click ( function () {
    $( this ).parent ().remove ();
} );

newElement.insertAfter ( $( '#add' ) );
Jan Hančič