如何从php循环中获取多个文本框的值并使用javascript

时间:2019-09-18 15:11:33

标签: javascript php html

我想要的是每一行都应该有其总和(row1 =价格x数量),因为数量变化总和应该自动更改(total = row1 + row2 + row3)以便所有行的总和。只有第一行才能实现。在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>

1 个答案:

答案 0 :(得分:1)

首先,id属性为HTML元素指定唯一ID(该值在HTML文档中必须唯一)。您有三个带有id="price"的字段,三个带有id="quantity"的字段和三个带有id="result"的字段,这是无效的,因此应删除那些id(s)。

现在,您将必须通过getElementsByClassName使用它们的类名来访问这些字段。由于所有字段都将form-control作为其公共类,因此下面的代码可以完成这项工作。并将所有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);
});