Reputation: 111
I am still a beginner, and I tried to set up dynamic event handlers on input of type(text) in <td>
in a dynamic html table, with the 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. The value of i(as displayed in console.log) is NOT what it is supposed to be, that is, 0 to 4 successively, but always 5. But elsewhere I use similar patterns like in the example below, and it 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 somebody help identify the problem here? It's driving me crazy.
Upvotes: 0
Views: 38
Reputation: 1231
I have a different tricky approach:
$(function(){
//First, just build the table AND SAVE THE iterator in an tag atribute
var table = "<tr>";
for(var i=0; i<5; i++){
table += '<td><input type="text" name="vote['+i+']" data-id="'+i+'"> </td>';
}
table += "</tr>";
$("#table").html(table);
// On event 'keyup', get the iterator saved in attrbute ( data-id ) and use it :)
$("#table").on("keyup", "input[type='text']", function() {
var i = $(this).attr("data-id");
calculate(i);
});
});
function calculate(i){
console.log("Called to: "+i);
}
Following this, you can separate the building-html function( .html()
) from the event function ( 'keyup'
).
Upvotes: 0
Reputation: 4757
Its forming a closure. So, just enclose your click handler inside a self executing function which creates a new scope.
The problem is: since a variable in JavaScript has function level scope, your loop will overwrite the 'i' each time. Hence we can avoid this by having an anonymous function which creates a 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 an example:
Problem:https://jsfiddle.net/sandenay/ar5f5m4t/
Solution: https://jsfiddle.net/sandenay/m5p8740w/
Upvotes: 1
Reputation: 3760
This will work fine without loop also
$("#table").on("keyup", "input[type='text'][name^='vote']", function() {
console.log("called: "+i);
calculate(i);
});
Upvotes: 0