...

View Full Version : Dynamic Sum as you type (onkeypress?)



Darren
11-01-2006, 09:39 PM
This seems like an issue that has to have come up in the past, but I didn't find anything with a search, so here I am...

Here's a simplified version of what I'm trying to do


<HTML>
<HEAD>
<SCRIPT type="text/javascript">
function sumFields()
{
with( form1 )
{
var x;
x = Number(num1.value) + Number(num2.value);
total.value = x;
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM id=form1>
<INPUT id="num1" onkeypress="sumFields()">
<INPUT id="num2" onkeypress="sumFields()">

<INPUT id="total" readonly>
</FORM>

</BODY>

</HTML>
Now, the problem with this code is that the onkeypress event occurs before the change is actually made to the field value. So if I go to type in 123 into field one, then 234 into field two, the sum is always 'trailing' by one characters.


field 1 . . . field 2 . . . total
1 . . . . . . . . . . . . . 0
12. . . . . . . . . . . . . 1
123 . . . . . . . . . . . . 12
123 . . . . . 2 . . . . . . 123
123 . . . . . 23. . . . . . 125
123 . . . . . 234 . . . . . 146


Is there an easy way to get the behavior I'm after?

Thanks in advance,
Darren

bigtiger
11-01-2006, 09:55 PM
Did you tryed change onkeypress to onchange ?


<HTML>
<HEAD>
<SCRIPT type="text/javascript">
function sumFields()
{
with( form1 )
{
var x;
x = Number(num1.value) + Number(num2.value);
total.value = x;
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM id=form1>
<INPUT id="num1" onchange="sumFields()">
<INPUT id="num2" onchange="sumFields()">

<INPUT id="total" readonly>
</FORM>

</BODY>

</HTML>

Hope this help

Darren
11-01-2006, 10:04 PM
I did, but the onchange even occurs after the focus leaves the field. It doesn't update while you type. I was looking for a way to update the sum field as you enter each charcter into the other fields... no leaving the field required.

bigtiger
11-02-2006, 06:27 AM
hi, Darren, I do not know if this work for you. But this is a workaround for a low volume usage.


<HTML>
<HEAD>
<SCRIPT type="text/javascript">
function sumFields()
{
setTimeout("callback()", 10);
}

function callback()
{
with (form1)
{
var x;
x = Number(num1.value) + Number(num2.value);
total.value = x;
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM id=form1>
<INPUT id="num1" onkeypress="sumFields()">
<INPUT id="num2" onkeypress="sumFields()">
<INPUT id="total" readonly>
</FORM>

</BODY>

</HTML>

But I do think should have better solution out there
Hope this help
Eric,



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum