Skip to content

Instantly share code, notes, and snippets.

@sujeetkv
Last active September 24, 2019 11:57
Show Gist options
  • Save sujeetkv/da69ba85ba5e60a4ee2645daee750a39 to your computer and use it in GitHub Desktop.
Save sujeetkv/da69ba85ba5e60a4ee2645daee750a39 to your computer and use it in GitHub Desktop.
jQuery plugin to get sum of selected input values
(function ($) {
/**
* jQuery plugin to get sum of selected input values
* Usage syntax:
* $('selector').sum()
* $('selector').sum(initial_value)
* $('selector').sum(parse_type)
* $('selector').sum(parse_type, initial_value)
*/
$.fn.sum = function (parse_type, initial_value) {
var parseType = typeof parse_type === 'function' ? parse_type : parseFloat;
var initialValue = parseType(typeof parse_type !== 'function' ? parse_type : initial_value) || 0;
var mapper = function () {
return parseType($(this).val() || 0);
};
var reducer = function (accumulator, currentValue) {
return accumulator + currentValue;
};
return initialValue + this.map(mapper).get().reduce(reducer);
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment