Sandra Schlichting
Sandra Schlichting

Reputation: 25986

Why doesn't this execute on first click?

In this jsFiddle

http://jsfiddle.net/littlesandra88/RBU8K/

have I the following code

function addRemove(id) {
    alert("1");

    $('#'+id).toggle(function() {
    alert("2");
    $('#'+id).after('<tr id="details" ><td>It worked</td></tr>');

    }, function() {
    alert("3");
    $("#details").remove();    
    });
}

When clicking one time on "Details" it prints "1", but not "2" for some reason.

When the first click have been done, it works like it is supposed to.

But what's wrong, since the first click doesn't print out "2"?

And how can it be fixed?

Update

This is the solution

function addRemove(id) {

    if ($('#accTable').find("[id*='details']").length == 0) {   
    $('#'+id).after('<tr id="details" ><td>It worked</td></tr>');
    } else {
    $("table tr").remove("#details");
    }

}

Upvotes: 1

Views: 329

Answers (1)

Jan Hančič
Jan Hančič

Reputation: 53931

You are only attaching a event handler (the toggle thingy) when calling addRemove(), then after you click again the event handler gets triggered.

Upvotes: 3

Related Questions