Skip to content

Instantly share code, notes, and snippets.

@devoto13
Created November 26, 2014 18:41
Show Gist options
  • Save devoto13/67c477bc2e7538d289da to your computer and use it in GitHub Desktop.
Save devoto13/67c477bc2e7538d289da to your computer and use it in GitHub Desktop.
Dollars amount real-time update
(function ($) {
var DOLLARS = 20;
$.fn.dollars = function () {
$(this).each(function () {
var $table = $(this);
$table.find('tr:first-child th:not(:first-child)').each(function (index) {
var $label = $('<span/>').appendTo($(this)),
$fields = $table.find('td:nth-child(' + (index + 2) + ') input');
$fields.on('input', function () {
var used = Array.prototype.reduce.call($fields, function (sum, el) {
return sum + (parseInt(el.value, 10) || 0);
}, 0);
if (used > DOLLARS) {
$label.text(' ($' + (used - DOLLARS) + ' overused)')
.addClass('text-danger');
} else {
$label.text(' ($' + (DOLLARS - used) + ' left)')
.removeClass('text-danger');
}
});
$fields.eq(0).trigger('input');
});
});
}
})(jQuery);
jQuery(function ($) {
$('table').dollars();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment