简体   繁体   中英

How to sum and display total in a label using javascript

I am having a grid view as follows

 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.

在此处输入图像描述

My code for displaying amount onblur event is as follows

<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:

document.getElementById("total")

use the body onload event to append eventlisteners to the onblur event of your quantity textboxes. And while you're at it, use a namespace, a singleton, so you don't clutter the global namespace, like so:

<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:

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

</body>

you might want to do some validation on the quantity textboxes, but I leave that up to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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