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

我想要的是每一行都应该有它的总和(row1=price 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>


哈士奇WWW
浏览 234回答 1
1回答

MYYA

首先,该id属性为 HTML 元素指定了唯一的 id(该值在 HTML 文档中必须是唯一的)。您有三个字段 with id="price"、三个 withid="quantity"和三个 withid="result"无效,因此您应该删除那些id(s)。现在,您必须使用它们的类名访问这些字段getElementsByClassName。由于所有字段都form-control作为它们的公共类,下面的代码将完成这项工作。并将所有内容替换id="result"为class="result".$(document).ready(function(){&nbsp; var input = document.getElementsByClassName('form-control');&nbsp; var result = document.getElementsByClassName('result');&nbsp; var total = 0;&nbsp; for(var i=0; i<input.length; i+=2){&nbsp; &nbsp; var product = input[i].value * input[i+1].value;&nbsp; &nbsp; total += product;&nbsp; &nbsp; product = product.toLocaleString(undefined, {maximumFractionDigits:2});&nbsp; &nbsp; result[i/2].innerHTML = product;&nbsp; }&nbsp; total = total.toLocaleString(undefined, {maximumFractionDigits:2});&nbsp; $("#totals").html(total);});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript