PDA

View Full Version : window.onkeyup event does not work



kodt
06-14-2007, 07:15 PM
I have a form with 4 text input fields. The last one is the total of the previous three fields and should automatically calculate this value when a user enters data into any of the first 3.

Normally I would put an onkeyup="" event on the input elements and have that call the function. However, this form is automatically generated based upon information in an XML file. I can add some HTML and Javascript to the page via the XML file, but cannot directly modify the form elements. I am wondering if there is a way to run the calcIT() function below on every onkeyup event. The code below does not seem to be working. I know the calcIT function works correctly.

I have also tried document.onkeyup, and I have tried creating an Alert box in the calcNow function. Neither worked.



window.onkeyup=calcNow;

function calcNow {
calcIT(document.quizform.userans0.value, document.quizform.userans1.value, document.quizform.userans2.value);
}

function calcIT(v,a,b) {

var total, v2, a2, b2;
v2 = parseFloat(v)
a2 = parseFloat(a)
b2 = parseFloat(b)
total = (v2 + a2 + b2);

document.quizform.userans3.value = total;
}

codeexploiter
06-15-2007, 03:53 AM
Check the following code.



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<style type="text/css">

</style>
<script type="text/javascript">
function calcNow() {
calcIT(document.quizform.userans0.value, document.quizform.userans1.value, document.quizform.userans2.value);
}

function calcIT(v,a,b) {
var total, v2, a2, b2;
v2 = parseFloat(v)
a2 = parseFloat(a)
b2 = parseFloat(b)

if(isNaN(v2))
v2 = 0.0;
if(isNaN(a2))
a2 = 0.0;
if(isNaN(b2))
b2 = 0.0;

total = v2 + a2 + b2;
document.quizform.userans3.value = total;
}

window.onload = function() {
document.getElementById('userans0').onkeyup = calcNow;
document.getElementById('userans1').onkeyup = calcNow;
document.getElementById('userans2').onkeyup = calcNow;
} </script>
</head>
<body>
<form name="quizform">
Answer 1 <input type="text" name="userans0" id="userans0" /><br />
Answer 2 <input type="text" name="userans1" id="userans1" /><br />
Answer 3 <input type="text" name="userans2" id="userans2" /><br />
Total <input type="text" name="userans3" id="userans3" readonly="readonly" /><br />
</form>
</body>
</html>


I've indicated all the changes I've made to your code in blue. Please let me know if you have any problem in my code.

kodt
06-15-2007, 01:20 PM
Thanks, I was just missing the () when I called calcNow, however checking to see if the values are numbers was also a good idea.

You code works great, thanks again.