JQ - Lose Control After New Table


I wrote a program that serves no real purpose while trying to learn. It’s posted at http://centerproto.zapto.org/radproblem. I generate a simple table and everything works as expected. However, I have radio buttons that cause a like table to be generated. Afterward my mouse functions are inoperable. All new tables do generate correctly and the classes are identical to the original’s classes. The significant part of the code is:


$(document).ready(function() {
    generateTable($("#tbl"), 1, 3, 1);
    
    $('.inlibutton').click(function(){
        var valvalue= $('input[name=radbutton]:checked').val();
        $("#tbl").empty();
        generateTable($("#tbl"),1, 3, valvalue);
    }) //end .click;
  
    $('.tdCell, .chosenCell')
    .mouseenter(function(){
        var temp=$(this).text();
        $('.displayarea').text(temp);
        $(this).addClass("pointToCell");
    }) //end mouseenter
    
    .mouseleave(function(){
        $('.displayarea').empty();
        $(this).removeClass("pointToCell");
    }) //end mouseleave

Any insight would be appreciated.

When you do something like


$('.inlibutton').click(function(){...});

jquery inspects the current dom, and finds all elements which exist at that specific moment in time, that have that classname. It tells each of those existing elements to run your function if they get clicked.

If you later create new elements, it doesn’t matter whether or not these new elements have been given the same classname. They simply don’t know they should do something when clicked.

You can either tell the new elements after you create them, or, you can read up on jquerys live() method, which does some behind the scenes magic, using event delegation, so that all present, and future elements which match your selector, will run your function for the event.

Thanks, but let me be sure we’re clear on what’s happening. The generateTable() function is the same for all clicks and it assigns the classes ‘tdCell’ and ‘chosenCell’. The ‘.inlibutton’ is the class of the form containing the buttons. Too, the previous table is cleared (emptied) before a new one is generated. If any of that’s different from what you thought, does it make any difference in your comments? I’d appreciate any additional thoughts you have and I’ll resume my studies come morning. Thanks again!

My previous comment still stands.

I should have used

$('.tdCell, .chosenCell')
    .mouseenter(function(){

as the example in my explanation, but the concept is the same in any case.

In case you aren’t aware, $(“<td>”) creates a new dom element. This would be a good spot to assign event handlers to that element, so that it knows what to do when those events occur on it.

Obviously, there’s lots I don’t know yet. Thanks for the info.

I assigned the event handlers immediately after generating the new dom element. All worked well across multiple browsers. Thanks again!!