Sum of Arrays within Arrays using jquery and javascript

Discussion in 'JavaScript' started by neilfurry, Nov 12, 2016.

  1. #1
    Hello,



    Im hoping to get help from here,



    i have arrays of text fields that i need to get sums,..



    <div class='fldgroup'>
    
    <input type="text" name="fld[0]">
    
    <input type="text" name="fld[0]">
    
    <input type="text" name="fld[0]">
    
    <input type="text" name="sumfld[0]">
    
    <button>Add Another Field</button>
    
    </div>
    
    
    
    <div class='fldgroup'>
    
    <input type="text" name="fld[1]">
    
    <input type="text" name="fld[1]">
    
    <input type="text" name="fld[1]">
    
    <input type="text" name="sumfld[1]">
    
    <button>Add Another Field</button>
    
    </div>
    
    
    
    <button>Add Another  Field Group</button>
    Code (markup):




    how can i get the sum of all fld[0] and put it to sumfld[0] same as the fld[1] to sumfld[1],.. every text field is dynamically added using clone.,



    i hope somebody can help me with this....



    Thank you in advance...
     
    Last edited by a moderator: Nov 12, 2016
    neilfurry, Nov 12, 2016 IP
  2. hdewantara

    hdewantara Well-Known Member

    Messages:
    538
    Likes Received:
    47
    Best Answers:
    25
    Trophy Points:
    155
    #2
    It appears that the index i of fld also determines which fldgroup we currently see, and so you could apply a for loop to it:
    var fldgroups = document.getElementsByClassName('fldgroup');
    for(var i = 0; i < fldgroups.length; i++){
        //...
    }
    
    Code (JavaScript):
    And inside that loop, try get all the inputs, except sumfld:
    var inputs = fldgroups.getElementsByTagName('input'),
        sumfldIndex = inputs.length - 1,
        sum= 0;
    for(var j = 0; j < sumfldIndex; j++){
        sum += Number(inputs[j].value);
    }
    inputs[sumfldIndex].value = sum;
    Code (JavaScript):
     
    hdewantara, Nov 12, 2016 IP