Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Feb 2003
    Posts
    51
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Checkbox value - undefined

    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[i].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 "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
    [I]IF (x[i]=undefined){x=0} ?
    Can you help me? Is the script structure wrong? How can be done?

  2. #2
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,079
    Thanks
    0
    Thanked 257 Times in 253 Posts
    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;
    }

  3. #3
    New Coder
    Join Date
    Feb 2003
    Posts
    51
    Thanks
    0
    Thanked 0 Times in 0 Posts
    TH!!! It was simple !!! I always comlicate the simple things.


 

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •