简体   繁体   English

如何使用 javascript 在 label 中求和并显示总数

[英]How to sum and display total in a label using javascript

I am having a grid view as follows我有一个grid view如下

 Quantity    Description    Rate    Total
   1             ---         10      10
   2             ---         20      40

                             Label outside the `gridview`

I have written a javascript to display total now I would like to display the total like 10+40 and should display as 50 like that I will have some other ways what I need is I would like to display the total sum on Blur event of quantity textbox.我已经写了一个on Blur来显示总数,现在我quantity 10+40那样显示总数,应该像这样显示50文本框。

在此处输入图像描述

My code for displaying amount onblur event is as follows我的显示金额onblur事件的代码如下

<script type="text/javascript">
    function multiplication(txtQuantity, txtRate, txtAmount) {
        var weight = document.getElementById(txtQuantity).value;
        var rate = document.getElementById(txtRate).value;
        document.getElementById(txtAmount).value = weight * rate;
    }
</script>

In this script I would like to include the total在这个脚本中,我想包括总数

give the quantity textboxes a name like "quantity", then you can get them with:给数量文本框起一个像“数量”这样的名字,然后你就可以得到它们:

document.getElementsByName("quantity");

give your label an id, like "total", so you can get that with:给你的 label 一个 id,比如“total”,这样你就可以得到它:

document.getElementById("total")

use the body onload event to append eventlisteners to the onblur event of your quantity textboxes.使用 body onload 事件到 append 事件监听器到你的数量文本框的 onblur 事件。 And while you're at it, use a namespace, a singleton, so you don't clutter the global namespace, like so:当你使用它时,使用一个命名空间 singleton,这样你就不会弄乱全局命名空间,如下所示:

<script>
    var p = {
        onload: function() {
            var els_qty = document.getElementsByName("quantity");
            for(var i = 0, ceiling = qty_els.length; i < ceiling; i++) {
                qty_els[i].onblur = function() {
                    var total = 0;
                    for(var j = 0; j < ceiling; j++) {
                        total += Number(qty_els[j].value);
                    }
                    document.geTElementById("total").innerHTML = total;
                }
            }
        }
    };
</script>

to append the onload eventlistener, use the following:到append onload eventlistener,使用如下:

<body onload="p.onload()">

</body>

you might want to do some validation on the quantity textboxes, but I leave that up to you.您可能想对数量文本框进行一些验证,但我将其留给您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM