简体   繁体   中英

input array values sum using javascript

I have input fields like this

<input  name="unittotal[]" type="text" id="unittotal[]" onchange="sumofunittotal();" size="3"  />
<input  name="unittotal[]" type="text" id="unittotal[]"  onchange="sumofunittotal();"  size="3"  />
<input  name="unittotal[]" type="text" id="unittotal[]"   onchange="sumofunittotal();" size="3"  />
<input  name="unittotal[]" type="text" id="unittotal[]"   onchange="sumofunittotal();"  size="3"  />

. . .

<input name="total" type="text" id="total" value="">

if i enter value in unittotal field onchange the final text box value is should be sum of that unit total using javascript.

Here's the working demo for you.

You need not use duplicate id values for your HTML elements. Consider using class name instead. Refer the markup and the code that calculates the total. I hope its self-explanatory enough.

JavaScript:

function updateTotal() {
    var total = 0;//
    var list = document.getElementsByClassName("input");
    var values = [];
    for(var i = 0; i < list.length; ++i) {
        values.push(parseFloat(list[i].value));
    }
    total = values.reduce(function(previousValue, currentValue, index, array){
        return previousValue + currentValue;
    });
    document.getElementById("total").value = total;    
}

HTML:

<input type="text"  class='input' value="0" onchange='updateTotal();'>
<input type="text"  class='input' value="0" onchange='updateTotal();'>
<input type="text"  class='input' value="0" onchange='updateTotal();'>
<input type="text"  class='input' value="0" onchange='updateTotal();'>

<input name="total" type="text" id="total" value="">

Like this:

<input type="text" size="3" class="add" />
<input type="text" size="3" class="add" />
<input type="text" size="3" class="add" />
<input type="text" size="3" class="add" />
<hr>
<input type="text" size="3" id="sum" />

and the javascript:

(function () {

    var elms = document.querySelectorAll('.add'),
        arr = Array.prototype.slice.call(elms),
        onChange = function () {
            var result = 0;
            arr.forEach(function (el) {
                result = result + +el.value;
            });

            document.getElementById('sum').value = result;
        };

    arr.forEach(function (el) {
        el.addEventListener('change', onChange);
    });

}());

http://jsfiddle.net/65b6T/

try this , and see in detail in fiddle DEMO . HTML

<table width="300px" border="1" style="border-collapse:collapse;background-color:#E8DCFF">
    <tr>
        <td width="40px">1</td>
        <td>
            <input class="txt" type="text" name="txt" />
        </td>
    </tr>
    <tr>
        <td>2</td>
        <td>
            <input class="txt" type="text" name="txt" />
        </td>
    </tr>
    <tr>
        <td>3</td>
        <td>
            <input class="txt" type="text" name="txt" />
        </td>
    </tr>
    <tr>
        <td>4</td>
        <td>
            <input class="txt" type="text" name="txt" />
        </td>
    </tr>
    <tr>
        <td>5</td>
        <td>
            <input class="txt" type="text" name="txt" />
        </td>
    </tr>
    <tr>
        <td>6</td>
        <td>
            <input class="txt" type="text" name="txt" />
        </td>
    </tr>
    <tr id="summation">

        <td align="left">Total :</td>
        <td align="left"><span id="sum">0</span>

        </td>
    </tr>
</table>

Javascript:

 $(document).ready(function () {

     //iterate through each textboxes and add keyup
     //handler to trigger sum event
     $(".txt").each(function () {

         $(this).keyup(function () {
             calculateSum();
         });
     });

 });

 function calculateSum() {

     var sum = 0;
     //iterate through each textboxes and add the values
     $(".txt").each(function () {

         //add only if the value is number
         if (!isNaN(this.value) && this.value.length != 0) {
             sum += parseFloat(this.value);
         }

     });
     //.toFixed() method will roundoff the final sum to 2 decimal places
     $("#sum").html(sum.toFixed(2));
 }

Here is a DEMO for this solution. http://jsfiddle.net/jxJg7/1/ NOTES: It works only if your values are integers. I created a function that will force the user to put numbers only on the inputs Make sure you remove the duplicated IDs

<script type="text/javascript">
function sumofunittotal() {
    var total = 0;
    var cusid_ele = document.getElementsByClassName('inputtosum');
    for (var i = 0; i < cusid_ele.length; ++i) {
    if (!isNaN(parseInt(cusid_ele[i].value)) )
    total += parseInt(cusid_ele[i].value);  
    }
    document.getElementById('total').value=total;
}

function onlynumber(e) {
    if (e.shiftKey === true ) {
    if (e.which == 9) {
    return true;
    }
    return false;
    }
    if (e.which > 57) {
    return false;
    }
    if (e.which==32) {
    return false;
    }
    return true;
}
</script>

<input  name="unittotal[]" class="inputtosum" type="text" onchange="sumofunittotal();" onkeydown="return onlynumber(event);" size="3"  />
<input  name="unittotal[]" class="inputtosum" type="text" onchange="sumofunittotal();" onkeydown="return onlynumber(event);" size="3"  />
<input  name="unittotal[]" class="inputtosum" type="text" onchange="sumofunittotal();" onkeydown="return onlynumber(event);" size="3"  />
<input  name="unittotal[]" class="inputtosum" type="text" onchange="sumofunittotal();" onkeydown="return onlynumber(event);" size="3"  />
<input name="total" type="text" id="total" value="">

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