PDA

View Full Version : Checkbox value - undefined



Cris79
03-28-2003, 08:08 AM
I have problem with a form and checkbox here is the code:

<HTML>
<HEAD>
<TITLE></TITLE>
<script>
x = new Array()
function show(){
var f = document.f1
for (var i=0; i<f.elements.length; i++)
if(f.elements.checked==true){
x[i]=f.elements[i].value;
var z=parseInt(x[0])+parseInt(x[1])+parseInt(x[2])+parseInt(x[3])
document.f2.out.value=z
}
}
</script>
</HEAD>
<BODY>
<form name="f1">
<input type="checkbox" name="vas1" value="1">1<br>
<input type="checkbox" name="vas2" value="2">2<br>
<input type="checkbox" name="vas3" value="3">3<br>
<input type="checkbox" name="vas4" value="4">4<br>
</form>
<br>
<form name="f2">
<input type="text" name="out">
<input type="button" value="Show" onclick="show()">
</form>
</BODY>
</HTML>

The problem is if you dont check all the checkbos inf2 frame the result is NaN because the valule for the non checkbos is "[I]undefined". I use parseInt to convert the string "1" in the number "1".
How can I put in the undefined value the 0 value?
something like
IF (x[i]=undefined){x[i]=0} ?
Can you help me? Is the script structure wrong? How can be done?

glenngv
03-28-2003, 08:36 AM
is this what you need?

function show(){
var f = document.f1;
var total = 0;
for (var i=0; i<f.elements.length; i++)
if(f.elements[ i ].checked==true){
total+=parseInt(f.elements[i].value,10);
}
document.f2.out.value=total;
}

Cris79
03-28-2003, 08:53 AM
TH!!! It was simple !!!:o I always comlicate the simple things. :D