【问题标题】:Check box and jquery ajax复选框和 jquery ajax
【发布时间】:2012-09-18 15:57:50
【问题描述】:

我正在尝试创建一个模块,其中每当检查复选框时,数据库中指示的价格将被添加到总费用中,结果将显示。如何从数据库(sql)中获取值/插入 php 代码并显示所选框的结果?

<script>
function updateTextArea() { 
    var allVals = [];
    $('#c_b :checked').each(function() {
        allVals.push($(this).val());
    });
    $('#t').val(allVals)
}
$(function() {
    $('#c_b input').click(updateTextArea);
    updateTextArea();
});

index.php

$queryPaymentLab = "select * from requestedlab where patient_ID='6' AND paid='0'";
$resultPaymentLab = mysql_query($queryPaymentLab);
$countRowsPaymentLab=mysql_num_rows($resultPaymentLab);

if($countRowsPaymentLab > 0){
while($fetchLab=mysql_fetch_array($resultPaymentLab)){
    $labservice_ID=$fetchLab['labservice_ID'];

    $queryPrice = "select * from labservices where labservice_ID='".$labservice_ID."'";
    $resultPrice = mysql_query($queryPrice);
    $fetchPrice=mysql_fetch_array($resultPrice);

    $labService=$fetchPrice['labService'];
    $labPrice=$fetchPrice['labPrice'];
    $totalLab+=$labPrice;
    $totalHBill+=$labPrice;

    echo "<tr><td><input type='checkbox' name='labservice_ID' value='$labservice_ID'/></td>
    <td>Laboratory</td><td>$labService</td><td>$totalHBill</td></tr>";
}
}

显示总费用..

 $queryPrice = "select * from labservices where labservice_ID='".$labservice_ID."'";
    $resultPrice = mysql_query($queryPrice);

    while($fetchPrice=mysql_fetch_array($resultPrice)){   
        $labPrice=$fetchPrice['labPrice'];
        $total+=$labPrice;
    }

    echo "<strong>Total:</strong>
    <strong>$total</strong>";

【问题讨论】:

    标签: php jquery ajax checkbox


    【解决方案1】:

    为什么不考虑使用 HTML5 data 属性?

    HTML:

    <?php 
    // Use PHP to dynamically fetch the data-price values and generate the HTML below
    ?>
    <span class="item" data-price="100">...</span>
    <span class="item" data-price="90">...</span>
    <span class="item" data-price="130">...</span>
    
    USD: <span class="price">0</span>
    

    JS:

    function updateCost() {
        $('.item').each(
            function() {
                if ($(this).children('input:checkbox').is(':checked')) {
                    var oldPrice = parseInt($('.price').text());
                    var newPrice = oldPrice + parseInt($(this).data('price'));
                    $('.price').text(newPrice);
                }
            }
        );
     }
    
    • onchange 事件中为每个复选框调用 updateCost()
    • 确保取消选中复选框会适当地从总价中减去价格!
    • 不要忘记在提交时汇总并检查价格,否则您很容易出现欺诈性购买!

    这样您就可以避免不必要的 Ajax 并且代码保持简洁。抱歉,如果这不是您想要的,请告诉我,以便我能提供更好的帮助。

    如果您有某种市场,成本本身会实时更新,这将需要一些外部帮助。对于市场,只需调用一个 Ajax 函数来适当地更新每个项目的 data-price 属性! :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-08
      • 1970-01-01
      • 2013-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多