如何在ajax数据表中添加(数字总和),即使使用jquery添加了新行


How do I add (sum of numbers) within a data-table in ajax even if a new row is added with jquery

我试图使一个添加(或减法,如果需要)与ajax的php页面。

这个代码应该做的是把所有的价格加起来,然后用实时编辑表给我正确的总和。

如果用户改变了price的值,$price_total也会相应改变。

即使添加了新行,它仍然应该给出包含新行的新总和(显示在$price_total和$final_price_total中)。

我一直在想怎么做这件事,但我不知道怎么做。

$price_total和$final_price_total不会被保存到数据库中

这是我目前得到的代码:

index . php

<html>
      <head>
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
      </head>
      <body>
           <div class="container">
                <br />
                <br />
                <br />
                <div class="table-responsive">
                     <div id="live_data"></div>            
                </div>
           </div>
      </body>
 </html>
 <script>
$(document).ready(function(){
    function fetch_data(){
        $.ajax({
            url:"select.php",
            method:"POST",
            success:function(data){
                $('#live_data').html(data);
            }
        });
    }
    function formatDecimal(val, n) {
        n = n || 2;
        var str = "" + Math.round ( parseFloat(val) * Math.pow(10, n) );
        while (str.length <= n) {
            str = "0" + str;
        }
        var pt = str.length - n;
        return str.slice(0,pt) + "." + str.slice(pt);
    }
    fetch_data();
    function edit_data(id, text, column_name){
        $.ajax({
            url:"edit.php",
            method:"POST",
            data:{
                id:id,
                text:text,
                column_name:column_name
            },
            dataType:"text",
            success:function(data){
                /*alert(data);*/
            }
        });
    }
    $(document).on('click', '#btn_add', function(){
        /* this function would also add the prices to the table*/ 
        var price = $('#price').text();
        var final_price = $('#final_price').text();
        if(price == ''){
            alert("Enter Price");
            return false;
        }
        if(final_price == ''){
            alert("Enter Final Price");
            return false;
        }
        $.ajax({
            url:"insert.php",
            method:"POST",
            data:{price:price, final_price:final_price},
            dataType:"text",
            success:function(data){
                alert(data);
                fetch_data();
            }
        })
    });
    $(document).on('blur', '.price', function(){
        var id = $(this).data("id1");
        var price = $(this).text();
        edit_data(id, price, "price");
        /*I'm trying so that I can add the new input price with the old total to give the exact value*/
        $total = parseFloat( price ) + parseFloat( $('#price_total').value );
        $('#price_total').value = formatDecimal(total);
    });
    $(document).on('blur', '.final_price', function(){
        var id = $(this).data("id2");
        var final_price = $(this).text();
        edit_data(id, final_price, "final_price");
    });

});

select.php

<?php
$connect = mysqli_connect("localhost", "root", "", "test_db");  
$output = '';  
$sql = "SELECT * FROM tbl_sample ORDER BY id DESC";  
$result = mysqli_query($connect, $sql);
$output .= '
    <div class="table-responsive">
    <table class="table table-bordered">
    <tr>
    <th width="10%">Id</th>
    <th width="40%">Price</th>
    <th width="40%">Final Price</th>
    <th width="10%">Delete</th>
    </tr>';
if(mysqli_num_rows($result) > 0){
    $final_price_total = 0;
    $price_total = 0;
    while($row = mysqli_fetch_array($result)){
        $output .= '
            <tr>
            <td>'.$row["id"].'</td>
            <td class="price" data-id1="'.$row["id"].'" contenteditable>'.$row["price"].'</td>
            <td class="final_price" data-id2="'.$row["id"].'" contenteditable>'.$row["final_price"].'</td>
            <td><button type="button" name="delete_btn" data-id3="'.$row["id"].'" class="btn btn-xs btn-danger btn_delete">x</button></td>
            </tr>
            ';
            $final_price_total += $row["final_price"];
            $price_total += $row["price"];
        }
        $output .= '
            <tr>
            <td></td>
            <td class="price_total" id="price_total" name="price_total" value="'.$price_total.'" contenteditable>'.$price_total.'</td>
            <td class="final_price_total" id="final_price_total" name="final_price_total" value="'.$final_price_total.'" contenteditable>'.$final_price_total.'</td>
            <td></td>
            </tr>
            ';
        $output .= '
            <tr>
            <td></td>
            <td id="price" contenteditable></td>
            <td id="final_price" contenteditable></td>
            <td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button></td>
            </tr>
            ';
}
else{
    $output .= '<tr>
    <td colspan="4">Data not Found</td>
    </tr>';
}
$output .= '</table>
</div>';
echo $output;
?>

从问题评论中的小讨论中,我发现了这个变量错字:

 $total = parseFloat( price ) + parseFloat( $('#price_total').value );
 $('#price_total').value = formatDecimal(total);

在第二行你使用total而不是$total

如果你检查浏览器的错误控制台,你会看到一个关于未声明的变量total的错误。

编辑:经过进一步的讨论,你想知道如何在JavaScript中遍历表并加总数。试试这个:

var newTotal = 0.0;
$('.price').each(function() {
    newTotal += parseFloat($(this).text());
});

如果您在编辑查找时这样做,那么您可以在final_price字段中使用newTotal变量来代替您正在使用的$total变量。