简体   繁体   中英

Javascript to display sum of 50 textboxes values

I have around 50 textboxes in my webpage, where user can enter numeric values. As they enter the numbers I have to display the total of all the numbers in another label.

Is there an AJAX or Javascript solution?

So can someone please help me to find what is the best way to achieve this?

With jQuery

var total = 0;
$('input:text').each(function() {
    total = total + parseInt($(this).val());
});

With plain JavaScript

var total = 0;
var inputs = document.getElementsByTagName('input');
for(var i=0; i < inputs.length; i++)
{
    var input = inputs[i]
    if (input.type == 'text') {
         total = total + parseInt(input.value);
    }
}

What you would need to do is set an event listener (onkeyup maybe) on every box that calls a single function. That function iterates over all the boxes and sets the appropriate value.

http://jsfiddle.net/HqUDw/

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