Alexia Hurley
Alexia Hurley

Reputation: 85

Using Jquery to change class on dynamic generated element

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.

Upvotes: 0

Views: 2249

Answers (3)

Adil
Adil

Reputation: 148140

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.

Upvotes: 0

kinduff
kinduff

Reputation: 142

Another alternative using find, live and toggleClass

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

JsFiddle

Upvotes: 0

Ram
Ram

Reputation: 144689

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')
})

Upvotes: 4

Related Questions