-4

I have a PHP page displaying the results of a MySQL query. The User can change the quantity Intended input and by clicking on Get Total Button, user can see the result of Item Rate * Qty Intended. So, that total can be used for creating a voucher for the user.

Can anybody guide me on how to add this functionality to my existing page.

enter image description here

My code currently is shown below:

<?php
  include 'functions.php'; //for connection
?>
<table>
<tr>
<th>Select</font></th>
<th>Item Desc</th>
<th>Item Specification</th>
<th>Item Rate</th>
<th>Qty Intented</th>
</tr>

<?php
  $sql1 = mysql_query("SELECT * from item
            where item ='stationeries'")
  while ($row = mysql_fetch_array($sql1, MYSQL_ASSOC)) {
?>
<tr>
  <td><input type="checkbox" name="sel" /></td>
  <td><?php echo $row['item']; ?></td>
  <td><?php echo $row['specification']; ?></td>
  <td><?php echo $row['rate']; ?></td>
  <td><input type="text" name="qty" class="toAdd" id="qty" value="0.0" /></td>
  </tr>


<?php
  }
?>
</table><br />
<input type="button" value="Get Total" />
<input type="text" id="total" />
4

2 回答 2

1

为您的表格和“获取总计”按钮提供一个 ID:

<table id="cart">

<input id="calculateTotal" type="button" value="Get Total" />

将此脚本放在<head>您的页面中:

$(function() {
    $('#calculateTotal').click(function() {
        var total = 0;
        $('#cart tr:gt(0)').each(function() {
            total +=
                parseFloat($(this).find('td:eq(3)').text()) * 
                parseFloat($(this).find('input:last').val());
        });

        // display total in textbox
        $('#total').val(total);
    });
});

如果您想限制用户只能输入整数(例如,您不能购买一小部分肥皂),请将其添加到您的 jQuery 就绪函数中$(function() {

$('#cart').on('keyup', '.toAdd', function() {
    $(this).val( $(this).val().replace(/[^0-9]/, '') );
});

要将购物车总数格式化为小数点后两位:

total = parseInt(total * 100) / 100;

演示:http: //jsfiddle.net/WDxej/2/

于 2013-07-31T09:56:02.903 回答
0

我假设您只想在客户端执行此计算,因此使用 JavaScript。由于您还标记了 jQuery,我假设您有它可用...

为了进行计算,您需要能够从 dom 中检索数据。为此,您可以向 HTML 元素添加属性,在这种情况下,您可能只需添加类即可。

<tr class="item-row">
    <td><input type="checkbox" name="sel" class="item-checkbox" /></td>
    <td><?php echo $row['item']; ?></td>
    <td><?php echo $row['specification']; ?></td>
    <td class="item-rate"><?php echo $row['rate']; ?></td>
    <td><input type="text" name="qty" class="toAdd item-qty" id="qty" value="0.0" /></td>
</tr>

现在您可以轻松地从 dom 中选择您想要的数据并进行计算:

// in button onclick handler
$('.item-row').each(function () {
    // this now references the row
    var selected = $(this).find('.item-checkbox').is(':checked');
    var rate = parseFloat($(this).find('.item-rate').html());
    var qty = parseFloat($(this).find('.item-qty').html());

    // do calculations...

});

另外,在 JS 中做数学时要小心,尤其是浮点数

于 2013-07-31T09:51:54.013 回答