Previously, I explained how to create a contact form. In this part, I’ll explain how to create a calculator form.
To parse the equation (separate the values from the operators), you need some sort of parsing routine. Those are very complicated to write. So, instead, I make the website programmer place the separate values and operators into an array, in the order of the equation. I figure, they already know and have access to those various parts. So, parsing done! Oh, just make sure the values are numbers and not strings.
Then I wrote a simple routine to evaluate the equation from the array. You can use operators **, *, /, +, -. These are evaluated based on mathematical rules – ** first, then * and / left to right, Then + and – left to right. I was going to provide for % (remainder), but who knew what order you wanted that evaluated in.
I provide input fields for all the values and operators. The operator fields are readonly, though you could not make them readonly and let the user enter their own equation. Because the keyboard operators threw off my vertical alignment, I display other similar symbols, but the value is still the keyboard operator.
But, your equation still might have nested equations: 1+2*(3+4). 3+4 is nested. Innermost equations are evaluated first. I used data-calceq to specify the level. For 3, +, 4, data-calceq=”2″. For 1, +, 2, *, data-calceq=”1″. Now I need somewhere to store the result of 3+4. I call this hidden input field xf_calc_resultN where N is the level number – in this case 2. xf_calc_result2 has data-calceq=”1″.
Now I call my routine to evaluate the form, passing the form id. Form has data-calceqs=”2″ (the number of equations). My routine gets all the children (descendants) of the form. It evaluates the equation where data-calceq=”2″. Then it evaluates the equation where data-calceq=”1″. If you had 10 equations, it would evaluate them from 10 to 1.
The result of equation 1 needs to go somewhere. I place it in an output field with id=xf_calc_result1.
If your formula’s not too complicated, you can use xf_calc. Otherwise, you’ll need to call xf_math_eval(equation_array) multiple times and piece together the results. You can still use hidden input fields for intermediate results.
Stay tuned. Next time, I’ll finish up with a menu form. Then I’ll tell you where you can find out more about xf_form.js.