Skip to content

Instantly share code, notes, and snippets.

@jdavidbakr
Created June 8, 2015 21:42
Show Gist options
  • Save jdavidbakr/695ffdb421dbf8001274 to your computer and use it in GitHub Desktop.
Save jdavidbakr/695ffdb421dbf8001274 to your computer and use it in GitHub Desktop.
JavaScript: Field Multiplier
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