Search code examples
javascriptqualtrics

Assigning onkeyup event to multiple objects at once


I am working with qualtrics and I am trying to customize their matrix control. I am trying to loop through a matrix with 8 rows and 4 columns where each cell contains a textbox and assign each textbox an onkeyup event like so:

for (var j=1; j< 9; j++){
        row_txt[j] = [];
        for (var k=1; k<5; k++){
            txt1= $('QR~QID2~'+j+'~'+k);
            txt1.onkeyup=function(){alert(j+','+k);};
        }
}

However, the onkeyup event returns "9,5" for each textbox changed. Why isn't it displaying the correct indices? How can I assign the same onkeyup event to multiple objects with the corresponding parameters j and k ?

Thank you


Solution

  • The issue with the value of j and k is that the actual keyup event occurs sometime in the future. When that event occurs, the values of j and k have gotten to the end of the for loop and thus all event handlers will show the same values.

    The usual way to fix this is by adding a closure that freezes the values of j and k separately for each event handler.

    for (var j=1; j< 9; j++){
        row_txt[j] = [];
        for (var k=1; k<5; k++){
            (function(j, k) {
                txt1= $('QR~QID2~'+j+'~'+k);
                txt1.onkeyup=function(){alert(j+','+k);};
            })(j, k);
        }
    }
    

    Also, I'm curious what you're doing with this:

    $('QR~QID2~'+j+'~'+k);
    

    That will create something like this:

    $('QR~QID2~1~9);
    

    Are you actually using HTML tags with that tagname or should this be a class name or an id (e.g prefaced with a . or #)?