我想要的是每一行都应该有它的总和(行 1 = 价格 x 数量)随着数量的变化总和应该自动改变(总计 = 行 1 + 行 2 + 行 3)所以所有行的总和。因为它我只能在第一行实现这一目标。在这里测试我的代码 https://malawiclinic.000webhostapp.com/
<form class="form-inline">
<?php
$sqlm="SELECT * FROM tbl_wishlist ORDER BY id DESC ";
$resultmn=mysqli_query($db,$sqlm);
$fcount=mysqli_num_rows($resultmn);
if ($fcount>0) {
$countprice=0;
while($found = mysqli_fetch_array($resultmn)) {
$product = $found['product'];
$qty = $found['Quantity'];
$price = $found['price'];
echo "
<div class='form-group'>
<label for='exampleInputName2'>$product</label>
<input type='text' class='form-control' id='price'
value='$price'>
</div>
<div class='form-group'>
<input type='number' class='input-text form-control'
id='quantity' value='$qty'>
</div>
<label for='exampleInputName2'>$
<span id='result'></span>
</label>";
}
} ?>
</form>
<script type="text/javascript">
$(document).ready(function(){
$(document).on("input",".input-text", function(){
var x = document.getElementById("quantity").value;
var x1 = document.getElementById("price").value;
var total = x1 * x;
var totals = total.toLocaleString(undefined,
{maximumFractionDigits:2});
$("#result").html(totals);
$("#totals").html(totals);
});
});
</script>
最佳答案
首先,id
属性为 HTML 元素指定了一个唯一的 id(该值在 HTML 文档中必须是唯一的)。你有三个 id="price"
字段,三个 id="quantity"
字段,三个 id="result"
字段不是有效,因此您应该删除那些 id
(s)。
现在,您必须通过 getElementsByClassName
使用它们的类名来访问这些字段。由于所有字段都将 form-control
作为它们的公共(public)类,下面的代码将完成这项工作。并将所有 id="result"
替换为 class="result"
。
$(document).ready(function(){
var input = document.getElementsByClassName('form-control');
var result = document.getElementsByClassName('result');
var total = 0;
for(var i=0; i<input.length; i+=2){
var product = input[i].value * input[i+1].value;
total += product;
product = product.toLocaleString(undefined, {maximumFractionDigits:2});
result[i/2].innerHTML = product;
}
total = total.toLocaleString(undefined, {maximumFractionDigits:2});
$("#totals").html(total);
});
关于javascript - 如何从 php 循环中获取多个文本框的值并使用 javascript 对它们求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57995964/