admin管理员组

文章数量:1313111

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.

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.

Share Improve this question asked Jan 7, 2014 at 5:22 Saravanan M PSaravanan M P 291 silver badge10 bronze badges 8
  • What's your question? – m59 Commented Jan 7, 2014 at 5:23
  • (Not question related) Your inputs have the same ID. programmers.stackexchange./questions/127178/… – Nico Commented Jan 7, 2014 at 5:24
  • if i enter number in unittotal text box. i want sum of value in that total input text box – Saravanan M P Commented Jan 7, 2014 at 5:25
  • All those input are precisely the same. Javascript won't be able to distinguish one from the other without some hacky trickery. – zeantsoi Commented Jan 7, 2014 at 5:25
  • If you want the sum, then write yourself a little code that'll give you the sum. – cookie monster Commented Jan 7, 2014 at 5:26
 |  Show 3 more ments

4 Answers 4

Reset to default 6

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/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/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="">

本文标签: input array values sum using javascriptStack Overflow