Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 07-02-2003, 02:38 AM   PM User | #1
autumnnn
New to the CF scene

 
Join Date: Aug 2002
Posts: 3
Thanks: 0
Thanked 0 Times in 0 Posts
autumnnn is an unknown quantity at this point
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>
autumnnn is offline   Reply With Quote
Old 07-02-2003, 03:02 AM   PM User | #2
cheesebagpipe
Regular Coder

 
Join Date: Nov 2002
Posts: 596
Thanks: 0
Thanked 0 Times in 0 Posts
cheesebagpipe is an unknown quantity at this point
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>
cheesebagpipe is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 03:10 PM.


Advertisement
Log in to turn off these ads.