如何从动态文本框中乘以和计算值?

时间:2017-07-17 07:16:25

标签: javascript jquery

我想将service_cost * service_days的值相乘,但service_cost和service_days是动态的,可能会重复多次。之后,我想计算所有乘法结果的总和,并将其分配给小计文本框。

<div class="form-group">
    <label for="place" class="col-sm-2 control-label">Services</label>
    <div class="col-md-10" id="check" style="padding-left: 0px !important;">
        <?php
            $sql = "SELECT * FROM service_ipd ORDER BY service_id ASC";
            $q = $pdo->query($sql);
            while($row = $q->fetch(PDO::FETCH_ASSOC))
            {
        ?>
        <div class="col-sm-5" style="margin-bottom:10px;">
            <div class="input-group date">
                <div class="input-group-addon">
                    <input type="checkbox" value="<?php echo $row['service_id']; ?>" name="service[]" id="service">
                </div>
                <input type="place" class="form-control" name="" id="" placeholder="" value="<?php echo $row['service_name']; ?>" disabled="true">
            </div>
        </div>
        <div class="col-sm-2">
            <div class="input-group">
                <input type="text" class="form-control" name="service_cost[]" id="service_cost" value="<?php echo $row['service_cost']; ?>" placeholder="" readonly>
            </div>
        </div>
        <div class="col-sm-2">
            <div class="input-group">
                <input type="text" class="form-control" name="service_days[]" id="service_days" placeholder="">
            </div>
        </div>
        <div class="clearfix"></div>
        <?php } ?>
    </div>
</div>
<input type="name" class="form-control" name="invoice_generation_date" id="sub_total" placeholder="Sub Total">

什么是最好的解决方案?请帮忙。

2 个答案:

答案 0 :(得分:0)

考虑一下:

<input name='items[1][service_day]'>
<input name='items[1][service_cost]'>
<!-- and for second item: -->
<input name='items[2][service_day]'>
<input name='items[2][service_cost]'>

现在,您可以循环使用包含array

service array项目
$total = 0;
foreach($_POST['items'] as $item){
        $multiply = $item['service_day'] * $item['service_cost'];
        $total += $multiply;
}

答案 1 :(得分:0)

首先,您不应该使用相同的ID创建多个输入。我会为每个输入ID添加一个索引或其他内容。 如果你使用jQuery,你可以试试这样的东西:

$(document).ready(function () {
   var total = 0;
   $.each($('input[name=service_cost[]]'), function(k, cost){
      $.each($('input[name=service_days[]]'), function(k, day){
         total += $(cost).val() * $(day).val();
      });
   });
   $('#sub_total').val(total);
};

或者您也可以使用PHP:

$sql = "SELECT * FROM service_ipd ORDER BY service_id ASC";
$q = $pdo->query($sql);
$total = 0;
while($row = $q->fetch(PDO::FETCH_ASSOC)){
    $total += $$row['service_cost'] * $row['service_day'];
}

<input type="name" class="form-control" name="invoice_generation_date" id="sub_total" value="<?= $total ?>" placeholder="Sub Total">