- Form iteration function not working properly
- 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);
- }
- }
- }
- <!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>
- e.elements.calculate.onclick = function(e) {
- return function() {
- var hours = e.elements.hours.value;
- var rate = e.elements.rate.value;
- alert(hours * rate);
- }
- }(e);
- e.elements.calculate.onclick = function(e) {
- var hours = this.elements.hours.value;
- var rate = this.elements.rate.value;
- alert(hours * rate);
- }.bind(e);
- forEach(document.forms, function(form) {
- form.elements.calculate.onclick = function() {
- var hours = form.elements.hours.value;
- var rate = form.elements.rate.value;
- alert(hours * rate);
- }
- });
- function forEach(list, callback) {
- for (var i= 0, n= list.length; i<n; i++)
- callback(list[i]);
- }
- for (var i= document.forms.length; i-->0;)
- document.forms[i].elements.calculate.onclick= calculate_click;
- function calculate_click() {
- var hours = this.form.elements.hours.value;
- var rate = this.form.elements.rate.value;
- alert(hours * rate);
- }