Hi, I've created the code below which automatically adds two fields together (drop-down boxes) , without the need for a submit or input button. Now, I am trying to do the same again, but this time instead of having drop-down boxes, i need to have text input boxes. (eventually i will be adding monetary values together). So far, i've not had any luck, but would really appreciate some help or advice. ----------- <script type="text/javascript"><!-- function updatesum() { document.form.sum.value = (document.form.sum1.options[document.form.sum1.selectedIndex].text-0) + (document.form.sum2.options[document.form.sum2.selectedIndex].text-0); } //--></script> <body> <form name="form" > Select a number: <select name="sum1" onChange="updatesum()"> <option selected>0<option>1<option>2<option>3<option>4 <option>5<option>6<option>7<option>8<option>9 </select> and another number: <select name="sum2" onChange="updatesum()"> <option selected>0<option>1<option>2<option>3<option>4 <option>5<option>6<option>7<option>8<option>9 </select> Their sum is:</th> <td><input name="sum" readonly style="border:none" value="0"> </form> </body> ---------------- Thanks! Ian
Try using following js <script type="text/javascript"><!-- function updatesum() { document.form.sum.value = document.form.sum1.value + document.form.sum2.value; } //--></script> Code (markup): HTML will be <body> <form name="form" > Enter a number: <input name="sum1" onChange="updatesum()" /> and another number: <input name="sum2" onChange="updatesum()" /> Their sum is:</th> <td><input name="sum" readonly style="border:none" value="0"> </form> </body> Code (markup): Not tested but should work. Hope this helps
Thank-you! This works fine except it concatenates the two numbers together, so 4+4 gives 44 instead of 8. I have remedied this by changing the line (added bits in red): document.form.sum.value = (document.form.sum1.value -0) + (document.form.sum2.value -0); } ... and this now works perfectly.
Oh, i forget that "+" operator is also use to concat variables in JS, please add it to my rep if you find it useful
In the future, just parse it to an int before adding document.form.sum.value = parseInt(document.form.sum1.value) + parseInt(document.form.sum2.value); Javascript will let you use + as an adder or a string concatenator. It defaults to a string if it's not sure, which is why you get 44 instead of 8
This works great, but how would you format the resulting sum? I assume toFixed(2); would work, but where in the function would you apply this filter?
Huh...just one thing, you need to make sure that the value in the field is a number not text, I have a similar feature in one of my web apps and the safest thing is to stop the user entering anything that is not (0 to 9 -.) you can do the test onKeyDown NEVER trust the user to enter a numeric value, human factor is a funny thing