Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 6th, 2012  |  syntax: None  |  size: 1.88 KB  |  hits: 11  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Form iteration function not working properly
  2. window.onload = function(){
  3.     calculateSavings();
  4. }
  5.  
  6. function calculateSavings(){
  7.     for (i = 0; i < document.forms.length; i++) {
  8.         var e = document.forms[i];
  9.         e.calculate.onclick = function() {
  10.             var hours = e.hours.value;
  11.             var rate = e.rate.value;
  12.             alert(hours * rate);
  13.         }
  14.     }
  15. }
  16.        
  17. <!doctype html>
  18. <html>
  19. <body>
  20. <form>
  21.   <label for="hours">Hours: </label><input type="text" id="hours" name="hours">
  22.   <label for="rate">Rate: </label><input type="text" id="rate" name="rate">
  23.   <input type="button" name="calculate" value="Calculate">
  24.   <div id="savings"></div>
  25. </form>
  26. <form>
  27.   <label for="hours">Hours: </label><input type="text" id="hours" name="hours">
  28.   <label for="rate">Rate: </label><input type="text" id="rate" name="rate">
  29.   <input type="button" name="calculate" value="Calculate">
  30.   <div id="savings"></div>
  31. </form>
  32. </body>
  33. </html>
  34.        
  35. e.elements.calculate.onclick = function(e) {
  36.     return function() {
  37.         var hours = e.elements.hours.value;
  38.         var rate = e.elements.rate.value;
  39.         alert(hours * rate);
  40.     }
  41. }(e);
  42.        
  43. e.elements.calculate.onclick = function(e) {
  44.     var hours = this.elements.hours.value;
  45.     var rate = this.elements.rate.value;
  46.     alert(hours * rate);
  47. }.bind(e);
  48.        
  49. forEach(document.forms, function(form) {
  50.     form.elements.calculate.onclick = function() {
  51.         var hours = form.elements.hours.value;
  52.         var rate = form.elements.rate.value;
  53.         alert(hours * rate);
  54.     }
  55. });
  56.  
  57. function forEach(list, callback) {
  58.     for (var i= 0, n= list.length; i<n; i++)
  59.         callback(list[i]);
  60. }
  61.        
  62. for (var i= document.forms.length; i-->0;)
  63.     document.forms[i].elements.calculate.onclick= calculate_click;
  64.  
  65. function calculate_click() {
  66.     var hours = this.form.elements.hours.value;
  67.     var rate = this.form.elements.rate.value;
  68.     alert(hours * rate);
  69. }