Click to See Complete Forum and Search --> : If....Else


bloke
08-26-2003, 09:15 AM
Hi

Can one of you clever people tell me what is wrong with this:

<SCRIPT LANGUAGE=javascript>
var total = 0;

function addVal(obj)
{
if (isNan(obj))
{
alert("Please enter only numerical characters")
obj.focus()
return false
}
else
{
total = parseFloat(total) + parseFloat(obj.value);
document.frm.totalvalue.value = Math.abs(total);
}
}
</script>

The else part of it works fine alone and is activated with onBlur it's just that if someone tabs out of an empty field, the totalvalue field becomes NaN therefore I only want to activate the sum and return if there is a value entered into the field.

I get an 'object expected' error and I'm just about ready to throw in the towel!

Any help much appreciated.

Cheers

ggriffit
08-26-2003, 10:09 AM
Try changing the is to

isNaN(obj.value)

to check the value of the field and not the field object.

bloke
08-26-2003, 10:12 AM
Just tried that, same error I'm afraid.... :-(

AdamBrill
08-26-2003, 10:17 AM
Try this:<script type="text/javascript">
var total = 0;
function addVal(obj){
if (isNaN(obj.value)){
alert("Please enter only numerical characters")
obj.focus()
return false
}else{
if(obj.value==0){
document.frm.totalvalue.value = total;
}else{
total = parseFloat(total) + parseFloat(obj.value);
document.frm.totalvalue.value = Math.abs(total);
}
}
}
</script>

bloke
08-26-2003, 10:20 AM
Works a treat, give yourself a shiny!

While I'm at it, don't suppose you know how to limit the return value to 2 decimal places do you? Eg, I've just tried entering 10 into 2 of the fields and 10.99 into a third field and the result is 30.990000000000002 !!

Cheers

AdamBrill
08-26-2003, 10:24 AM
Change this line:

document.frm.totalvalue.value = Math.abs(total);

To this:

document.frm.totalvalue.value = Math.abs(total).toFixed(2);

bloke
08-26-2003, 10:32 AM
Once again, works just great. Made one last change:

<script type="text/javascript">
var total = 0;
function addVal(obj){
if (isNaN(obj.value)){
alert("Please enter only numerical characters")
obj.focus()
return false
}else{
if(obj.value==0){
document.frm.totalvalue.value = Math.abs(total).toFixed(2);
}else{
total = parseFloat(total) + parseFloat(obj.value);
document.frm.totalvalue.value = Math.abs(total).toFixed(2);
}
}
}
</script>

...and all is well

Many thanks

AdamBrill
08-26-2003, 10:34 AM
I'm glad to help. :)