Form iteration function not working properly

Posted by Moses on Stack Overflow See other posts from Stack Overflow or by Moses
Published on 2011-01-06T21:46:31Z Indexed on 2011/01/06 21:53 UTC
Read the original article Hit count: 208

Filed under:
|
|

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:

<!doctype html>
<html>
<body>
<form>
  <label for="hours">Hours: </label><input type="text" id="hours" name="hours">
  <label for="rate">Rate: </label><input type="text" id="rate" name="rate">
  <input type="button" name="calculate" value="Calculate">
  <div id="savings"></div>
</form>
<form>
  <label for="hours">Hours: </label><input type="text" id="hours" name="hours">
  <label for="rate">Rate: </label><input type="text" id="rate" name="rate">
  <input type="button" name="calculate" value="Calculate">
  <div id="savings"></div>
</form>
</body>
</html>

I'm sure this is a really basic question but the solution is completely eluding me at this point.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about html