loops - How to set up jQuery dynamic event handlers properly? -
i still beginner, , tried set dynamic event handlers on input of type(text) in <td>
in dynamic html table, following code:
for(var i=0; i<5; i++){ table += '<td><input type="text" name="vote['+i+']"></td>'; $("#table").on("keyup", "input[type='text'][name='vote["+i+"]']", function() { console.log("called: "+i); calculate(i); }); }
it did not work. value of i(as displayed in console.log) not supposed be, is, 0 4 successively, 5. elsewhere use similar patterns in example below, , works.
$.each(array_parties, function(i, objparty) { var stationid = objstation.stationid; var partyid = objparty.partyid; table += '<td><input type="text" name="items['+stationid+']['+partyid+']"></td>'; $("#table").on("keyup", "input[type='text'][name='items["+stationid+"]["+partyid+"]']", function() { calculatetotalbyparty(json, partyid, khumid); }); });
please, can identify problem here? it's driving me crazy.
its forming closure. so, enclose click handler inside self executing function creates new scope.
the problem is: since variable in javascript has function level scope, loop overwrite 'i' each time. hence can avoid having anonymous function creates new scope.
for(var i=0; i<5; i++){ (function(j){ table += '<td><input type="text" name="vote['+j+']"></td>'; $("#table").on("keyup", "input[type='text'][name='vote["+j+"]']", function(){ console.log("called: "+j); calculate(j); }); })(i) }
as example:
problem:https://jsfiddle.net/sandenay/ar5f5m4t/
solution: https://jsfiddle.net/sandenay/m5p8740w/
Comments
Post a Comment