Math calculation of checkbox values on the same page

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Calimero
Forum Contributor
Posts: 310
Joined: Thu Jan 22, 2004 6:54 pm
Location: Milky Way

Math calculation of checkbox values on the same page

Post by Calimero »

Intro:

I have a form, and PHP_SELF command

I have 3 checkboxes

<input type="checkbox" name="check1" value="25">
<input type="checkbox" name="check2" value="20">
<input type="checkbox" name="check3" value="15">

As you noticed VALUE field is different

And PHP code
GET for each of these

$value1='';
$value2= $check1 + $check2 + $check3;


The Problem:

I need the script to add values of any checked checkboxes on the page BUT also to present it on the same page (is it possible without loading the page again and loosing whats checked and what not)


Ex:

check1 (I checked it)

check2 (I checked it)

check3 (Not checked)

Output on the same page should be 45, but also the checkboxes that are checked should remain checked.

Thanks Ahead !
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

Not with PHP it isn't you have to reload the page for the new data to get parsed. You can keep the the data in the checkboxes though by doing something like '

Code: Select all

<?
if (!empty($value)) { echo "checked"; } // inside the checkbox
?>
althought i recommend putting everything into an array and using a foreach statement to sort that all out.

and to get the value of all the checked boxes

Code: Select all

<?php

foreach ($_POST["checkboxname"] as $checkbox)
{
    if (!empty($checkbox))  
    {
         $totalvalue += $checkbox;
    }
}

?>
To be honest I'm not sure if that's the correct way to do it but maybe it will give u an idea
User avatar
Calimero
Forum Contributor
Posts: 310
Joined: Thu Jan 22, 2004 6:54 pm
Location: Milky Way

...

Post by Calimero »

<if !empty ...>

where to place it in the checkbox ??!?!

so no way to combine Javascript (although I dont know how to do it in that way either) with PHP to do it on the same page ?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

Code: Select all

<input type="checkbox" name="check3" value="15" <? if (!empty($value)) { echo "checked"; } ?>>
You can do it with javascript. PHP is serverside and it parses the php before then outputs (what the user sees) on loading/refreshing.
If you don't mind having it reload once the form is submitted simply try that foreach statement at the top of your page.
Post Reply