javascript JQuery 乘以表行的输入值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11789683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:20:38  来源:igfitidea点击:

JQuery multiply input values of table rows

javascriptjquerymodel-view-controllerjquery-selectors

提问by antar

I want to calculate each row's total price by multiplying individual row's inputs and then finally calculate a grand total by adding all the total values of the Total column using JQuery. I am only getting the first row to display total when I enter values. Any help will be greatly appreciated.

我想通过将单个行的输入相乘来计算每一行的总价,然后通过使用 JQuery 将 Total 列的所有总值相加来最终计算总计。当我输入值时,我只让第一行显示总数。任何帮助将不胜感激。

     <script type="text/C#" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
         $(document).ready(function () {
            $(".txtMult").each(function () {
                $(this).keyup(function () {
                    multInputs();
                });
            });
           });

           function multInputs() {
               var mult = 0;
               $(".txtMult").each(function () {
                   var $val1 = $('#val1').val();
                   var $val2 = $('#val2').val();
                   var $total = ($val1 * 1) * ($val2 * 1)
                   $('#multTotal').text($total);
               });
           }

    </script>
    @using (@Html.BeginForm())
    {
        <table>
        <tr>
            <th>
                Quanity
            </th>
            <th>
                Unit Price
            </th>
            <th>
                Total
            </th>
        </tr>
        @for (int i=0; i < 5; i++)
        {

            <tr>
                <td>
                    <input class ="txtMult" name="txtEmmail" id="val1"  />
                </td>
                <td>
                    <input class ="txtMult" name="txtEmmail" id="val2"/>
                </td>
                <td>
                    <span id="multTotal">0.00</span>
                </td>
            </tr>

    }
<tr>
    <td colspan="3" align="right">
        Grand Total# <span id="grandTotal">0.00</span>
    </td>
</tr>
    </table> 
    }

enter image description here

在此处输入图片说明

回答by nnnnnn

Your html is invalid: the idattribute is supposed to be unique but you are repeating the same three ids in every row. The easiest way to fix this is to change your inputs to have class="val1"and class="val2"instead of id="val1"and `id="val2", and change your row total to have class="multTotal". I'd also move the txtMultclass to each of the tr elements with the inputs in them, for ease of selecting those rows:

您的 html 无效:该id属性应该是唯一的,但您在每一行中都重复了相同的三个 ID。解决此问题的最简单方法是将您的输入更改为 have class="val1"andclass="val2"而不是id="val1"and `id="val2",并将您的行总数更改为 have class="multTotal"。我还将txtMult类移动到每个带有输入的 tr 元素,以便于选择这些行:

        <tr class="txtMult">
            <td>
                <input name="txtEmmail" class="val1"  />
            </td>
            <td>
                <input name="txtEmmail" class="val2"/>
            </td>
            <td>
                <span class="multTotal">0.00</span>
            </td>
        </tr>

...and then change the selector in your jQuery code to select by class in the context of the current row. Note also that you don't need an .each()loop to bind the .keyup()handlers to the elements that match your selector, just use $("someselector").keyup():

...然后将 jQuery 代码中的选择器更改为在当前行的上下文中按类进行选择。另请注意,您不需要.each()循环将.keyup()处理程序绑定到与您的选择器匹配的元素,只需使用$("someselector").keyup()

 $(document).ready(function () {
       $(".txtMult input").keyup(multInputs);

       function multInputs() {
           var mult = 0;
           // for each row:
           $("tr.txtMult").each(function () {
               // get the values from this row:
               var $val1 = $('.val1', this).val();
               var $val2 = $('.val2', this).val();
               var $total = ($val1 * 1) * ($val2 * 1);
               // set total for the row
               $('.multTotal', this).text($total);
               mult += $total;
           });
           $("#grandTotal").text(mult);
       }
  });

Working demo: http://jsfiddle.net/nnnnnn/5FpWC/

工作演示:http: //jsfiddle.net/nnnnnn/5FpWC/

回答by Sarowar

Let add a class into the table.

让我们in向表中添加一个类。

At first add a change event to all inputs of the table. On change of a input field multiply all inputs of same row and update the multTotaland grandTotal

首先向表的所有输入添加更改事件。在输入字段更改时乘以同一行的所有输入并更新multTotalgrandTotal

$(function(){
            $('.in input').change(function(){
                var p=$(this).parent().parent() //get the parent of changed input
                var m=p.find('input.txtMult') //find all input of the row
                var mul=parseFloat($(m[0]).val()*$(m[1]).val()).toFixed(2) //multiply them
                var res=p.find('.multTotal') // get corresponding multTotal
                res.html(mul); //show the result
                var total=0;
                $('.in .multTotal').each(function(){
                    total+=parseFloat($(this).html())
                }) //calculate grand total
                $('.in #grandTotal').html(parseFloat(total).toFixed(2)) //show grand total
            });
        })

check this at jsfiddle

jsfiddle检查这个

If need to process more than 2 fields change

如果需要处理2个以上的字段更改

var mul=parseFloat($(m[0]).val()*$(m[1]).val()).toFixed(2) //multiply them

to

var mul=1;
$(m).each(function(){
  mul*=$(this).val()
})
mul=parseFloat(mul).toFixed(2)