0

I have a script that dynamically generates a grid by using a table.

//createGrid(height, width);
createGrid(1, 2);
//one row with 2 cols

Which creates this:

<table>
    <tr>
        <td></td>
        <td></td>
    </tr>
</table>

I need an onclick event for the td tags that add/changes their class. I've tried a few solutions to no avail. Any ideas? I'm not great at Jquery.

2
  • 2
    i doubt you tried anything.. if you typed your question into google, you would have the answer right away -> see Commented Oct 27, 2012 at 20:55
  • possible duplicate of Can't click on the table created with jquery Commented Oct 27, 2012 at 21:05

3 Answers 3

4

For dynamically-generated elements, events should be delegated, from one of static parents of the element or document object, you can use on method:

$(document).on('click', 'td', function(){
   $('.selected').removeClass('selected');
   $(this).addClass('selected')
})
Sign up to request clarification or add additional context in comments.

Comments

0

Another alternative using find, live and toggleClass

$("table").find("td").live("click", function() {
    $(this).toggleClass("selected");
});​

JsFiddle

1 Comment

As of jQuery 1.7 live method is deprecated.
0

You can use on jquery function for binding the dynamically generated item for event delegation, It binds the existing elements with event and It will also bind element which are added dynamically. $('td').click(function(){}); will only bind the existing element but not the added dynamically after he binding.

$(document).on("click", "td", function(){
     alert("clicked");
});

Delegated events

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers, reference.

You can change document with some parent element selector.

3 Comments

I'd add in why this differs from $('td').click().
I did as he requires for dynamically generated elements
I mean, explain how this is different and why you would use this instead of the regular .click() handler.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.