javascript - How do I make this event handler more flexible -
i have jquery function i've written live calculation based on user input. works i'm wondering if there more scalable solution. every time have new equation run needs same functionality (live updating), end copying script, changing equation variables. equation same use same function request.
let me know if there better way or if i'm approaching right.
http://jsfiddle.net/darcyvoutt/zhow0uky/
var formcalc = function (input, multiplier, output) { var reloadcalc = function () { var formula = parsefloat($(input).val()) * parsefloat($(multiplier).val()); $(output).val(formula.tofixed(0)); }; $(document).ready(function () { $(input).on("keyup", function () { reloadcalc(); }); $(input).trigger("keyup"); }); }; formcalc('.input', '.multiplier', '.output');
unscalable parts of code
variables
(input, multiplier, output)
decimal places
.tofixed(0)
formula
var formula = parsefloat($(input).val()) * parsefloat($(multiplier).val());
add argument reloadcalc
:
var formcalc = function (input, output, reloadcalc) { input.on("keyup", function() { output.val(reloadcalc(input.val())); }).trigger("keyup"); }; $(document).ready(function() { formcalc($('.input'), $('.output'), function(input) { return (parsefloat(input) * parsefloat($('.multiplier').val()).tofixed(0); }); //...other formcalc calls });
now, given have input element $('#in')
, output element $('#out')
, , function f(input)
can do:
formcalc($('#in'), $('#out'), f);
Comments
Post a Comment