Recently I have a lot of task from my several client that ask me to convert their excel spreadsheet into fully working web based apps. Everything is fine when I build the form using standard jQuery event to trigger the calculation, getting value from each field, pass the calculation result to the target field, etc. But things become very slow and make my browser not responsive when the form contain lot of field and the calculation script start their work, triggering blur event on every field that need to be calculated, etc, etc, till I noticed that I was the fool one 😀 (I don’t know if I was a noob)
Then, I decide to do some research by googling and stackoverflowing :D, write some calculation plugin. It’s help me quite a lot finishing ma task in relative less time, but the fool things happen again, it’s running very slow on complex spreadsheet with only standard math calculation 😀
Now I rewrite all process from the beginning, and put the alpha release to github.
Let’s start using this plugin to build our calculator, everything is simple from now on, just write your form, define the formula, and we are done!
Build your form structure
The first step that need to be done, of course, build our html form. We can write as complex as we want, or as simple as kindergarten homework and let jQuery Calx do the rest.
Says we want to build simple total price calculator, we need to specify the form id, assign unique id to each field, and assume that total price formula is (quantity * price)*(1-discount) where discount is in decimal value (like 0.15 for 15%)
<form id="calx"> Price :<br /> <input type="text" id="price" /><br /> Qty :<br /> <input type="text" id="qty" /><br /> Discount :<br /> <input type="text" id="discount" /><br /> Total :<br /> <input type="text" id="total" data-formula="($price*$qty)*(1-$discount)" /><br /> </form>
We are done with the form structure and the formula, now let’s write down the script
Wait! Don’t we write calculation script!?
Yes, but it is the fact, we just need to define the formula inside the data-formula attribute <input> tag, and calx will parse and do the calculation, and the code above should look like this