My function is supposed to iterate all forms in the document, and bind an onclick function to each 'calculate' element int he form. The problem is, the function that executes on any of the click events executes in the context of the the last i in the loop.
Here is the JavaScript that I'm using:
window.onload = function(){
calculateSavings();
}
function calculateSavings(){
for (i = 0; i < document.forms.length; i++) {
var e = document.forms[i];
e.calculate.onclick = function() {
var hours = e.hours.value;
var rate = e.rate.value;
alert(hours * rate);
}
}
}
And here is the HTML it is attached to:
I'm sure this is a really basic question but the solution is completely eluding me at this point.
Here is the demo of the problem I'm experiencing: http://jsfiddle.net/KcNWy/ Are you open to using jQuery? Would ease the DOM manipulation.
以上就是Form iteration function not working properly的详细内容,更多请关注web前端其它相关文章!