Calculate Or Auto Sum the Value Using Checkbox with JavaScript and PHP/MySQL
Submitted by argie on Tuesday, February 11, 2014 - 11:37.
In this tutorial I will teach you on how to calculate or auto sum the total value of the product's price using checkbox with javascript and PHP/MySQL.
To understand this, follow the steps bellow.
Hope this code will help you. The running version of this tutorial can be found in the zip folder.
Creating Our Database
First we are going to create our database which stores our data. To create a database: 1. Open phpmyadmin 2. Then create database and name it as "tutorial". 3. After creating a database name, click the SQL and paste the following code.- CREATE TABLE IF NOT EXISTS `checkbox` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `name` varchar(100) NOT NULL,
- `price` int(11) NOT NULL,
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=11;
Creating our Database Connection
Next step is to create a database connection and save it as "connect.php". In this Step, we will write our connection script in PDO format.- <?php
- /* Database config */
- $db_host = 'localhost';
- $db_user = 'root';
- $db_pass = '';
- $db_database = 'tutorial';
- /* End config */
- $db = new PDO('mysql:host='.$db_host.';dbname='.$db_database, $db_user, $db_pass);
- $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- ?>
Creating Our Display
The code bellow will retrieve data from our database table and display the data in checkbox list. The code bellow include our javascript that automatically get the sum of the checkbox being check. Copy the code bellow and save it as "index.php".- <?php
- include('connect.php');
- $sadsdsd = $db->prepare("SELECT count(*) FROM checkbox");
- $sadsdsd->execute();
- $rowaas = $sadsdsd->fetch(PDO::FETCH_NUM);
- $wapakpak=$rowaas[0];
- ?>
- <script type="text/javascript">
- function UpdateCost() {
- var sum = 0;
- var gn, elem;
- for (i=0; i<<?php echo $wapakpak ?>; i++) {
- gn = 'sum_m_'+i;
- elem = document.getElementById(gn);
- if (elem.checked == true) { sum += Number(elem.value); }
- }
- document.getElementById('totalcost' ).value = sum.toFixed(0);
- }
- window.onload=UpdateCost
- </script>
- <?php
- include('connect.php');
- $result = $db->prepare("SELECT * FROM checkbox");
- $result->bindParam(':userid', $res);
- $result->execute();
- for($i=0; $row = $result->fetch(); $i++){
- ?>
- <INPUT TYPE="checkbox" NAME="items[]" value="<?php echo $row['price'] ?>" id="sum_m_<?php echo $i ?>" onclick="UpdateCost()" style="width: 21px;"><?php echo $row['name'] ?>--------<?php echo $row['price'] ?><br>
- <?php
- }
- ?><br>
- Total Cost : <input type="text" name="sen" id="totalcost" value="">
Comments
Add new comment
- Add new comment
- 2231 views