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?

2

2 Answers 2

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");
});
Sign up to request clarification or add additional context in comments.

Comments

1

You need to change te first line of your function:

$("body").on("click","td",function(){

Comments

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.