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 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Aug 2002
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Angry adding and subtracting checkboxes

    hi,

    I have a set of checkboxes and I want the script to add the values when checked but subtract when unchecked.

    I can do the check part but have no idea how to deduct from the total when someone unchecks the box(es).

    <HTML>
    <HEAD>
    <script type="text/javascript">
    function test(val){
    var all = 0;

    el = document.form1.total;
    all += parseInt(el.value) + parseInt(val);


    document.form1.total.value = all;

    }

    </script>


    </HEAD>
    <BODY>

    <form name="form1">
    $1 <input type="checkbox" name="check1" value="1" onClick="test(1)"> <BR>
    $2 <input type="checkbox" name="check2" value="2" onClick="test(2)"> <BR>
    $3 <input type="checkbox" name="check3" value="3" onClick="test(3)"> <BR>
    <BR><BR>
    <input type="text" name="total" value="0">





    </form>


    </BODY>
    </HTML>

  • #2
    Regular Coder
    Join Date
    Nov 2002
    Posts
    596
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Code:
    <html>
    <head>
    <script type="text/javascript">
    
    function sum(oCheckbox) {
         var fieldnames = ['check1' , 'check2' , 'check3']; //fields to sum, in array
         var field, total = 0, oForm = oCheckbox.form; //initialize total, get form object
         for (var i=0; i<fieldnames.length; ++i) { //loop
              field = oForm.elements[fieldnames[i]]; //get element
              if (field.checked)                     //checked?
                  total += parseInt(field.value);    //add it
       }
         oForm.elements.total.value = '$' + total;   //output
    }
    
    </script>
    </head>
    <body>
    <form name="form1">
    $1 <input type="checkbox" name="check1" value="1" onclick="sum(this)"><BR>
    $2 <input type="checkbox" name="check2" value="2" onclick="sum(this)"><BR>
    $3 <input type="checkbox" name="check3" value="3" onclick="sum(this)">
    <BR><BR>
    <input type="text" name="total" value="$0">
    </form>
    </body>
    </html>


  •  

    Posting Permissions

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