I would like to add some JavaScript to do the following.
I would have 3 fields like this.
<input type="text" name="a" />
<input type="text" name="b" />
<input type="hidden" name="c" />
say if I entered 100 in the first field and 19 in the second field.
it would divide 100 by 19 and round it up to no decimal places, and then replace the value of the third hidden field by the answer, so in the case it would be (100/19) 5.26... rounded up to 6
however I am not sure how to actually implement this.
You do this by binding an eventlistner to the from element. You either create your own (Javascript native event handlers) or use your favorit javascript framework. My example is for using the jQuery jQuery bind method javascript framework.
Say your form looks like this;
You can access the form like this;
You can trigger the action by adding a button that can be clicked, or setting the form's submit action.
Edit: Doesn't round up, not sure how to do that :(
After the form elements:
This recalculates on each key press, remove the
keyup
binding if you don't want that.Add a unique
id
to each input and usedocument.getElementById
to avoid any ambiguity withname
. If this form is never going to be submitted you can omitname
entirely.Math.ceil()
will returnNaN
if either value cannot be read as a number, orInfinity
if you divide by zero. You may wish to check for these conditions and write a different value.A nice easy method is to pass the form to a function, and allow that function to do the calculation.
The form should look like:
and the javascript:
Working example here --> http://jsfiddle.net/azajs/
Edit: This can also be done when the form is submitting by having a similar call in the onsubmit of the form:
A dumbed-down way, which assumes your form is document.forms[0]:
EDIT: Math.round => Math.ceil