简体   繁体   中英

How to save the value of the checked checkbox to the database

I have here checkboxes that have a different prices and each have a different titles. When the user clicks the checkbox, it will view the price in the total field. When the user now clicks the save button, I want now to save the total to the database and save the titles of the checked checkbox to categories. The titles that will be save to the one row of the database must be separated by comma (,).

This is my HTML codes:

<!DOCTYPE html>
<html>
<head>
    <meta charset=utf-8 />
    <title></title>
    <link rel="stylesheet" type="text/css" media="screen" href="css/master.css" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <!--<script type="text/javascript" src="js/jquery.min.js"></script>-->
    <!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
</head>
<body>
    <form action="" method="post">
        <input type="checkbox" name="checkbox1" value="₱20"> Red </br>
        <input type="checkbox" name="checkbox1" value="₱30"> Blue </br>
        <input type="checkbox" name="checkbox1" value="₱40"> Green </br>
        </br></br>
        Total: <input type="text" name="total" readonly>
        <input type="submit" name="save" value="SAVE">
    </form>
    <script type="text/javascript">
    $(function(){
        //bind the change event to the checkboxes
        $('input[name="checkbox1"]').change(function(){
            var total = 0;
            //get value from each selected ckeck box
            $('input[name="checkbox1"]:checked').each(function(){
                var tval = $(this).val();
                //remove ₱ sign from value
                //convert it to a flot
                //plus it to the total
                total += parseFloat(tval.replace("₱",""));                
            });
            //finally display the total with a ₱ sign
            $('input[name="total"]').val("₱ " + total);
        });
    });
    </script>
</body>
</html>

I don't have any idea in how to save the titles of the checkboxes to one row (CATEGORY) of the database. The total price must be save too in the TOTAL field in the database.

Table name: PRODUCTS

Columns: CATEGORY, TOTAL

Example data saved in the database:

CATEGORY:[Red, Blue]

TOTAL: [50]

Give them different names

<input type="checkbox" name="Red" value="₱20"> Red </br>
<input type="checkbox" name="Blue" value="₱30"> Blue </br>
<input type="checkbox" name="Green" value="₱40"> Green </br>

and change your jquery a little bit:

//bind the change event to the checkboxes
$('input[name="checkbox"]').change(function(){..}

then access the attribute name:

var name = $(this).attr("name");

DEMO


$(function(){
    var total = 0;
    var colors = "";
    $("input[type=checkbox]").change(function(e) {

        var selected_color = $('input[type=checkbox]:checked');
        colors = selected_color.map(function() {
            return $(this).attr("name");
        }).get().join(', ');
        //alert(colors);


         selected_color.each(function(){
           var tval = $(this).val();
           total += parseFloat(tval.replace("₱",""));                
        });
        //alert(total);
    });

    $( "form" ).submit(function( event ) {
        $.ajax({
          type: "POST",
          url: "your_script.php",
          data: { category:colors, total: total},
          success:  function(data) {
                  alert('success'); 
          }
        });
    });
});

PHP

echo $_POST['categor'];
echo $_POST['total'];

As for the insert provide this is straight for forward, you did not specify which driver you use, but you can consult @Ghost answer for mysqli

DEMO

If you need to colors, you need to get the next sibling from the binded checkbox, then you could create another hidden form for colors since you set the checkbox values as prices. Rough example:

<form action="" method="post">
    <input type="checkbox" name="checkbox1" value="20"> Red </br>
    <input type="checkbox" name="checkbox1" value="30"> Blue </br>
    <input type="checkbox" name="checkbox1" value="40"> Green </br>
    </br></br>
    <!-- hidden input colors -->
    <input type="hidden" name="colors" value="" />
    Total: <input type="text" name="total" readonly>
    <input type="submit" name="save" value="SAVE">
</form>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){

    var colors = [];
    //bind the change event to the checkboxes
    $('input[name="checkbox1"]').change(function(){
        var total = 0;
        //get value from each selected ckeck box
        $('input[name="checkbox1"]:checked').each(function(){
            var tval = $(this).val();
            total += parseFloat(tval);
        });
        //finally display the total with a ₱ sign
        $('input[name="total"]').val("₱ " + total);

        // handle colors
        var color = $.trim($(this)[0].nextSibling.nodeValue); // get the name
        var i = colors.indexOf(color);
        if(i != -1) {
            colors.splice(i, 1); // remove if unchecked
        } else {
            colors.push(color); // push if checked
        }
        var temp = colors.join(', ');
        $('input[name="colors"]').val(temp);

    });

});
</script>

The PHP:

<?php

$db = new mysqli('localhost', 'username', 'password', 'database');
$stmt = $db->prepare('INSERT INTO `PRODUCTS` (`CATEGORY`, `TOTAL`) VALUES (?, ?)');

if(isset($_POST['save'])) {
    $total = (int) str_replace('₱ ', '', $_POST['total']); // remove peso sign
    $colors = $_POST['colors'];
    $stmt->bind_param('si', $colors, $total);
    $stmt->execute();
}

?>

well this seems to be a problem to the super extraordinary label element!!! (i'm so stupid, i can't beat my impetus -.-)

you can put it in a label like this:

Red

so each label identify each checkbox

so you can (if it is PHP):

$labels = $_POST['labels'];

and supposing that you have a normalized DB like this(everything else is only play with strings):

| ID | CATEGORY |

for($i=0; $i < count($labels); $i++){ mysqli_query($con,"Insert into CATEGORY(categoryname) values(' "+$labels[$i]" '); "); }

PD: this code wasn't tested.

您需要编写一些服务器端代码,这些代码将采用表格数据并将其写入数据库-通常以PHP或ASP编写,并用SQL将数据写入数据库。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM