Someswara Siripuram Someswara Siripuram - 4 days ago 7
Javascript Question

Trigger click event on click of other element in a loop

I have a requirement where I have to fire click event on table header on click of other table header (2 different tables), but trigger is not fired on the table when in a loop. Although if I hardcode and bind the trigger to individual element, it works.

Currently, the JS looks like something like this:

var outsideHeaders = $("#header th");
var tableHeaders = $(".dataTable th");

for(var cnt = 0; cnt< outsideHeaders.length; cnt++)
{
$(outsideHeaders[cnt]).bind('click',function(){
$(tableHeaders[cnt]).trigger('click');
});
}


Please provide solution for this!

Updated:

This is how my code looks now:

var outsideHeaders = $("#header th");
var tableHeaders = $(".dataTable th");

for(var cnt = 0; cnt< outsideHeaders.length; cnt++)
{
(function(headerCnt){
$(outsideHeaders[headerCnt]).bind('click',function(){
$(tableHeaders[headerCnt]).trigger('click');
});
})(cnt);
}

Answer

The value of cnt inside the click event handler function is going to be equal to its last value in the for loop (in this case, whatever header.length was when the code executed) due to the way scoping in JavaScript works. You need to use a closure so that it maintains its value for that specific iteration:

$(document).ready(function() {
    var outsideHeaders = $("#header th");
    var tableHeaders = $(".dataTable th");

    for(var cnt = 0; cnt < outsideHeaders.length; cnt++)
    {
        (function(headerCount) {
            $(outsideHeaders[headerCount]).bind('click',function(){
                $(tableHeaders[headerCount]).trigger('click');
            });
        })(cnt);
    }
});

Note that I've wrapped the code in a $(document).ready() call. This will ensure that the elements exist when you try to select them.

Comments