Created
June 8, 2015 21:42
-
-
Save jdavidbakr/695ffdb421dbf8001274 to your computer and use it in GitHub Desktop.
JavaScript: Field Multiplier
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var FieldMultiplier = { | |
makeSum: function(e) { | |
/** | |
* Look for any elements with the same class as this one | |
* and sum them, multiplying by the multiplier attribute. | |
* The sum will go into the elements that match the sum attribute. | |
*/ | |
var sum = 0; | |
var sum_selector = '.'+e.getAttribute('class'); | |
var elements = document.querySelectorAll(sum_selector); | |
var length = elements.length; | |
for(var i = 0; i < length; ++i) { | |
var multiplier = elements[i].getAttribute('multiplier'); | |
var value = parseInt(elements[i].value); | |
if(value) { | |
if(multiplier) { | |
value *= multiplier; | |
} | |
sum += value; | |
} | |
} | |
var target_selector = e.getAttribute('sum'); | |
var target_elements = document.querySelectorAll(target_selector); | |
var target_length = target_elements.length; | |
for(var j = 0; j < target_length; ++j) { | |
target_elements[j].innerHTML = sum.toFixed(2); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment