Page 1 of 1

Displaying remainder of two values on the page

Posted: Tue Feb 08, 2011 3:29 am
by social_experiment
My code below determines the remainder of field1 - field2. The remainder is then written to another input field. From the example you will see i use onFocus() to display the remainder in the input field. My question : Is it possible to have the value written to the 'remainder' input field when a value has been entered into the 'field2' field (without clicking on the remainder field), and how? I've tried using onFocus and onBlur with the second field but it doesn't yield the results I am after.

Code: Select all

<script type="text/javascript">
function calculate_remainder()
{	
	var first_number = window.document.form1.fNumber.value;
	var second_number = window.document.form1.sNumber.value;
	var remainder_number;
	
	remainder_number = first_number - second_number;
	window.document.form1.remainder.value = remainder_number;	
}
/* */	
</script>
<form action="" method="post" name="form1" >
First value : <input type="text" name="first_number" id="fNumber" />
<br />
Second value : <input type="text" name="second_number" id="sNumber" />
<br />
Remainder of value 1 - value 2<input type="text" name="remainder" id="remainder" value="" 
onFocus="calculate_remainder();" />
<br />
<input type="submit" name="btn" value="Go" />
</form>
An additional question, if i want to write the remaining value to the page, not into a textbox, how do i go about it?

Re: Displaying remainder of two values on the page

Posted: Tue Feb 08, 2011 4:01 am
by Apollo
social_experiment wrote:My question : Is it possible to have the value written to the 'remainder' input field when a value has been entered into the 'field2' field (without clicking on the remainder field), and how?
Try the onchange or onkeypress events on field2 (and field1 for that matter).
An additional question, if i want to write the remaining value to the page, not into a textbox, how do i go about it?
Put something like <span id='remainder_goes_here'></span> where you want the remainder to appear in your html.

In your javascript function, do

Code: Select all

document.getElementById('remainder_goes_here').innerHTML = remainder_number;

Re: Displaying remainder of two values on the page

Posted: Tue Feb 08, 2011 4:32 pm
by social_experiment
Thanks for the reply Apollo. After those two fields there are more fields / checkboxes so when going to them (tabbing or clicking) the result is calculated and displayed. The latest code looks like this

Code: Select all

 Second value : <input type="text" name="second_number" id="sNumber"
onBlur="calculate_remainder();" />