1

I want to total the values of all input, but in the beginning there's only one input element and you add the clone(s) with a button. Actually I have two issues: 1. How to place the clone node always under the node before it. 2. How to total the values of all nodes.

Here's the code:

    function nambahData() {
        var a = document.getElementById("harga");
        var b = a.cloneNode(false);
        document.getElementById("form").appendChild(b);
    }

    function ditotal() {
        var x = document.getElementById("harga").value;
        var y = document.getElementById("harga").childNode.value;
        document.getElementById("total").value = parseInt(x) + parseInt(y);
    }
</script>

<div id="form">
    <input id="harga" type=number>
    <br>
</div>
<button onclick="nambahData()">add data</button>
<br>
<button onclick="ditotal()">total all</button>
<input id="total" type=number>

Hudoyo Danumurti
  • 75
  • 1
  • 3
  • 9
  • See here [Javascript Append Child AFTER Element](http://stackoverflow.com/questions/7258185/javascript-append-child-after-element) to put the clone in the desired position. – enhzflep Sep 19 '15 at 07:07
  • thankyou.. that's solving my first issue! but the second? :D – Hudoyo Danumurti Sep 19 '15 at 07:11
  • `var inputElems = document.getElementById('form').getElementsByTagName('input');` followed by `var total=0, i, n = inputElems.length;` which is then followed by a loop. `for (i=0;i – enhzflep Sep 19 '15 at 07:15

1 Answers1

1

Hope this helps you ..

window.nambahData = function() {
        var a = document.getElementsByName("harga");
        var b = a[0].cloneNode(false);
        document.getElementById("form").appendChild(b);
    }

window.ditotal = function() {
    var totalItems = 0;
    
    for(i=document.getElementsByName("harga").length-1;i>=0;i--)
    {
        var item = document.getElementsByName("harga")[i];
        totalItems += parseFloat(item.value);
    }
    document.getElementById("total").value = totalItems;
}
.inputStyle{
    display:block;
}
<div id="form">
    <input name="harga" type="number" class="inputStyle">
</div>
<button onclick="nambahData()">add data</button>
<br>
<button onclick="ditotal()">total all</button>
<input id="total" type=number>
Kishore Sahasranaman
  • 4,013
  • 3
  • 24
  • 50
  • 1
    @Kishore - Be aware that calling `document.getElementsByName` is a reasonably expensive operation that really shouldn't be performed during every iteration of the loop, much like the evaluation of the length of this array, which you've neatly evaluated just once - many people evaluate this instead of stuffing the value into a variable, with far fewer cleverly doing or as you have done, iterating through the array backwards. – enhzflep Sep 19 '15 at 07:32