0

I currently have a code that lets me "check" table cells, but the ones I create dynamically, don't apply to this.

$("td").click(function(){
        $(this).toggleClass("active");
    });

This code works great for static elements, but when I create one element...:

$("#boton").click(function(){
    var object = {
        name : $("#nombre").val(),
        dni : $("#dni").val(),
        telefono : $("#telefono").val()
    };

    if(count<5){
        count++;
        $("#tabla").append("<tr><td>"+object.name+"</td><td>"+object.dni+"</td><td>"+object.telefono+"</td>");
    }else{
        $("#boton").hide();
        alert("You added too much elements!");

    }

... that element is not selectable. The event doesn't fire for it. How can I change this?

Zerok
  • 1,323
  • 1
  • 24
  • 56
  • `$(document).on('click','td',function(){` tried this? – guradio Apr 13 '16 at 10:25
  • Possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – guradio Apr 13 '16 at 10:31

2 Answers2

2

In order to detect clicks on current and future instances you need to delegate the event to an element that does exist (eg the body):

$("body").on("click","td",function(){
    $(this).toggleClass("active");
});
Moob
  • 14,420
  • 1
  • 34
  • 47
1

You need to change te first line of your function:

$("body").on("click","td",function(){
pguetschow
  • 5,176
  • 6
  • 32
  • 45