Created
April 6, 2022 21:24
-
-
Save sam2332/29c32bb40d57fedbc388b34bdf77addc to your computer and use it in GitHub Desktop.
Total a list of dom elements and put the output in a destination
This file contains 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
function Totalizer() { | |
this.output = null | |
this.elements = [] | |
this.total = 0 | |
} | |
Totalizer.prototype.setOutput = function (output) { | |
this.output = $(output); | |
this.updateOutput() | |
} | |
Totalizer.prototype.updateOutput = function(){ | |
total = 0 | |
for (var i = 0; i < this.elements.length; i++) { | |
var ele = this.elements[i] | |
try { | |
var num = parseFloat(ele.val()) | |
if (isNaN(num)) { | |
num = 0 | |
} | |
total += num | |
} catch (error) { | |
console.error(error); | |
} | |
} | |
this.output.val((Math.round(total * 100) / 100).toFixed(2)); | |
this.output.change() | |
} | |
Totalizer.prototype.change = function (event) { | |
this.updateOutput() | |
event.target.value = parseFloat(event.target.value).toFixed(2); | |
}; | |
Totalizer.prototype.attach = function (lst_elements) { | |
for (var i = 0; i < lst_elements.length; i++) { | |
var ele = $(lst_elements[i]); | |
ele.change(this.change.bind(this)) | |
this.elements.push(ele) | |
} | |
this.updateOutput() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment