![](/img/trans.png)
[英]How can i multiply or add the values of a dynamic javascript input field
[英]How can I multiply and calculate values from dynamic text boxes?
我想將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">
什么是最好的解決方案? 請幫忙。
考慮一下:
<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;
}
首先,您不應創建具有相同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">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.