2

I have a piece of JQuery that creates a row in a table and in one of the cells there is an X that is surrounded by a class. When it is dynamically created and then clicked on the click listener does not fire. Here is the code.

$('#add').click(function() {
   $( '#table' ).append('<td class="x">X</td></tr>');
});
$('.x').click(function() {
  alert('Fired');
});
1
  • You're not adding "TR" at the start of your new row. Commented Aug 5, 2011 at 15:00

8 Answers 8

4

Since the <td> element does not yet exist when you register your event handler, you have to use live() or delegate() for the handler to be triggered later:

$(".x").live("click", function() {
    alert("Fired");
});
Sign up to request clarification or add additional context in comments.

Comments

0
$(".x").live("click", function()
{
   alert("Fired");
});

Live adds events to anything added later in the DOM as well as what's currently there.

Comments

0

Instead of

$('.x').click(function() {
  alert('Fired');
});

Change to this

$('.x').live('click', function() {
  alert('Fired');
});

It binds the click function to any created element with class x

Comments

0

You need to use the .live function for content that's dynamically generated.

so replace

$('.x').click(function() {

with

$('.x').live('click',function() {

Comments

0

You are first creating the listener to all .x elements (of which there are presumably zero), then later adding new .x elements.

There are two solutions: one is to use jQuery live, the other is to rewrite your code:

var xClickHandler = function() {
    alert('Fired');
};
$('#add').click(function() {
    $('#table').append(
        $('<td class="x">X</td></tr>').click(xClickHandler);
    );
});

Comments

0

Use live instead of click:

$('.x').live("click", function() {
    alert('Fired');
});

Comments

0

The html you are appending to the table has a typo, you have missed out the beggining tr tag:

$('#add').click(function() {
   $( '#table' ).append('<tr><td class="x">X</td></tr>');
});
$('.x').click(function() {
  alert('Fired');
});

Comments

0

I think you need to use the live method. http://api.jquery.com/live/

$('.x').live('click', function() {
  // Live handler called.
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.