0
function AddTableHeader(table, cells, newOrderby) {
    var head = table.createTHead();
    var row = head.insertRow(0);
    row.className = "SupplierDataTableTr";
    for (var s in cells) {
        var cell = null; 
        cell = document.createElement("th");
        cell.innerHTML = cells[s];
        cell.className = "SupplierDataTableTh";
        if (newOrderby != null && newOrderby[s] != null) {
            var ob = newOrderby[s];
            cell.onclick = function() { SetOrderBy(ob); AutoComplete(null, 'txtSearch'); };
            cell.style.cursor = "pointer";
        }

        row.appendChild(cell); 
    }
}

Inside the if-statement I set the variable ob = string in the array.. at the moment the array contains "SupplierNr", "Name", "Email", "Phone" and has the same order as the cells array.

The problem is that in the end the event on each <th> tag has the last newOrderby string attached to it which is "Phone". I've looped through this part in my debugger and it sets different orderby strings to each event in the loop, but for some reason all <th> elements gets the last eventhandler created. Why is this? The cell is created in a for loop and should be local, they shoulnd't have anything to do with eachother.

Anyone know what I might be doing wrong here?

Jonas B
  • 2,351
  • 2
  • 18
  • 26
  • Yes, we know :-) You'll get a bunch of answers really quickly, I predict. – Pointy Nov 25 '11 at 16:49
  • Oh also, totally different issue: using "for ... in" loops on arrays (or array-like things, like "arguments" or NodeList instances) is not a good idea. Much better to use a numeric index and a plain "for" loop. – Pointy Nov 25 '11 at 16:50
  • [Here](http://stackoverflow.com/questions/6163720/javascript-every-event-handler-defined-in-for-loop-is-the-same-uses-last-itera) is an older Stackoverflow question that is essentially the same problem. – Pointy Nov 25 '11 at 16:52

1 Answers1

1

If you're assigning event handlers in a loop, then you probably need to use a closure to ensure that it works properly. Otherwise you get the problem you're describing.

Similar issue and solution here: Event handlers inside a Javascript loop - need a closure?

Community
  • 1
  • 1
James
  • 13,092
  • 1
  • 17
  • 19
  • Thanks a lot this worked perfectly. And sorry all for duplicate question, I am bad with searching for the right keywords hehe. – Jonas B Nov 25 '11 at 17:03