Updating current money spent in a form with checkboxes. . .
I have a form with prices of items that PHP displays, and the items have check boxes next to them so that you can select or deselect them, and I was wondering how I would update the current cost when a user checks or unchecks a checkbox?
Thanks in Advance
You might hook a javascript function into the onclick event of the checkbox. When the checkbox is clicked, you can see what the state is, then add or subtract accordingly. This code should help, it's a working example:
Code:
<html>
<head>
<script language="javascript">
function changePrice(byAmount, state) {
var curVal = document.forms[0].total.value;
if (state) { // go up
var newVal = new Number(curVal)+new Number(byAmount);
} else { // go down
var newVal = new Number(curVal)-new Number(byAmount);
}
document.forms[0].total.value=newVal;
}
</script>
</head>
<body>
<form>
Check to add 10: <input type="checkbox" name="cb1" onclick="javascript:changePrice(10, this.checked)"/><br>
Check to add 20: <input type="checkbox" name="cb2" onclick="javascript:changePrice(20, this.checked)"/><br>
(unchecking the boxes subtracts)<br>
<input type="text" name="total" value="0"/>
(you can also put in your own value here, then use the checkboxes to change it)
</form>
</body>
</html>
By the way, this example is using an <input type="text">. . . however that is not required. You can actually change the value of virtually any text on the screen. The example is just the simplest way to implement what you've described.