2012-09-18 75 views
1

我想創建一個模塊,其中每當選中複選框時,數據庫中顯示的價格將被添加到總費用中,並顯示結果。如何從數據庫中獲取值(sql)/插入php代碼並顯示所選框的結果?複選框和jquery ajax

<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>"; 

回答

0

你爲什麼不考慮使用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); 
      } 
     } 
    ); 
} 
  • 呼叫updateCost()onchange事件每個複選框
  • 確保取消選中複選框減去總價格適當的價格!
  • 不要忘記總計和檢查提交價格,因爲你很容易欺詐購買否則!

這樣你避免不必要的Ajax和代碼保持清潔。對不起,如果這不是你想要的,讓我知道,所以我可以幫助更好。

如果您有某種市場,費用本身實時更新,則需要一些外部幫助。對於市場而言,只需調用一個Ajax函數即可更新各個項目的data-price屬性! :)