Calculate total of each row in the table

1

I'm trying to use JavaScript to dynamically calculate my prices multiplied by the quantities and result in the total for each row, but it calculates the grand total and plays in the last field of the Total column. Like the picture below:

    function calc(){ 

        var prices = new Array(); 
        var quantities = new Array(); 
        var counter = 0; 
        var total = 0; 
        var elements = document.getElementsByTagName('input'); 

        for(var i = 0; i < elements.length; i++){ 

        if(elements[i].getAttribute('special') == 'price'){ 
            prices[counter] = parseFloat(elements[i].value); 
        } 

        if(elements[i].getAttribute('special') == 'quantity'){ 
            quantities[counter] = parseInt(elements[i].value); 
            counter++; 
        } 

        }//Fim for 

        for(var i = 0; i < prices.length; i++){ 

            total += (prices[i] * quantities[i]); 

        }//Fim for 

        document.getElementById('total').value = total;

    }//Fim function
        <table border = '2'>
            <thead>
                <tr>
                    <th>Preço</th>
                    <th>Quantidade</th>
                    <th>Total</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><input type="text" name="valor_unitario[]" id="valor_unitario" value="2.50" special="price" /></td>
                    <td><input type="text" name="qnt[]" id="qnt" value="1" special="quantity" /></td>
                    <td> <input type="text" name="total" class="total" readonly="readonly" onclick="calc();" /> </td>
                    
                </tr>
                <tr>
                    <td><input type="text" name="valor_unitario[]" id="valor_unitario" value="5.50" special="price" /></td>
                    <td><input type="text" name="qnt[]" id="qnt" value="1" special="quantity" /></td>
                    <td> <input type="text" name="total" class="total" readonly="readonly" onclick="calc();" /> </td>
                </tr>
                <tr>
                    <td><input type="text" name="valor_unitario[]" id="valor_unitario" value="1.20" special="price" /></td>
                    <td><input type="text" name="qnt[]" id="qnt" value="1" special="quantity" /></td>
                    <td> <input type="text" name="total" class="total" readonly="readonly" onclick="calc();" /> </td>
                </tr>
                <tr>
                    <td><input type="text" name="valor_unitario[]" id="valor_unitario" value="9.80" special="price" /></td> 
                    <td><input type="text" name="qnt[]" id="qnt" value="1" special="quantity" /></td>
                    <td> <input type="text" name="total" id="total" readonly="readonly" onclick="calc();" /> </td>
                </tr>                      
            </tbody>
            
        </table>
    
asked by anonymous 26.04.2018 / 19:41

2 answers

1

Do not use identical ids

Just change the values of the inputs you calculate automatically.

var prices = document.querySelectorAll("[id^=valor_unitario]"),
    ammounts = document.querySelectorAll("[id^=qnt]"),
    subTotals = document.querySelectorAll("[id^=total]"),
    printSum = document.getElementById("PrintSoma");

function sumIt() {
    var total = 0;

    Array.prototype.forEach.call(prices, function (price, index) {
        var subTotal = (parseFloat(price.value) || 0) * (parseFloat(ammounts[index].value) || 0);
        
        subTotals[index].value = subTotal.toFixed(2);
        total += subTotal;

    });

    printSum.textContent = total.toFixed(2);
}

Array.prototype.forEach.call(prices, function (input) {
    input.addEventListener("keyup", sumIt, false);
});

Array.prototype.forEach.call(ammounts, function (input) {
    input.addEventListener("keyup", sumIt, false);
});

sumIt();
        <table border='2'>
            <thead>
                <tr>
                    <th>Preço</th>
                    <th>Quantidade</th>
                    <th>Total</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><input type="text" name="valor_unitario1" id="valor_unitario1" value="2.50" special="price" /></td>
                    <td><input type="text" name="qnt1" id="qnt1" value="1" special="quantity" /></td>
                    <td> <input type="text" name="total1" id="total1" class="total" readonly="readonly" /> </td>
                    
                </tr>
                <tr>
                    <td><input type="text" name="valor_unitario2" id="valor_unitario2" value="5.50" special="price" /></td>
                    <td><input type="text" name="qnt2" id="qnt2" value="1" special="quantity" /></td>
                    <td> <input type="text" name="total2" id="total2" class="total1" readonly="readonly" /> </td>
                </tr>
                <tr>
                    <td><input type="text" name="valor_unitario3" id="valor_unitario3" value="1.20" special="price" /></td>
                    <td><input type="text" name="qnt3" id="qnt3" value="1" special="quantity" /></td>
                    <td> <input type="text" name="total3" id="total3" class="total1" readonly="readonly" /> </td>
                </tr>                     
            </tbody>
            
        </table>
<table>
    <tr>
        <td><span id="PrintSoma">0.00</span>

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

Any HTML element can have an id attribute. The value of this attribute must be unique within the document - two elements in the same document can not have the same ID. You can select an element based on this unique ID with the document object's getElementById () method.

With Jquery

var prices = $("input[id^=valor_unitario]"),
    amounts = $("input[id^=qnt]"),
    subTotals = $("input[id^=total]"),
    printSum = $("#PrintSoma");

function sumIt() {
    var total = 0;

    prices.each(function(index, price) {
        var subTotal = (parseFloat(price.value) || 0) * (parseFloat(amounts.eq(index).val()) || 0);

        subTotals.eq(index).val(subTotal.toFixed(2));
        total += subTotal;
    });

    printSum.text(total.toFixed(2));
}

prices.on("keyup", sumIt);
amounts.on("keyup", sumIt);

sumIt();
  

[id^=valor_unitario]") - selects elements that have the specified attribute ( id ) with a value that begins exactly with a given string ( valor_unitario ). It could also be valor_

Attribute Starts With Selector [name ^="value"]

    
26.04.2018 / 20:58
1

You can simplify doing so ...

let preco = []
let qtd = []
let total = []

function calc(indice, self){
  let valorUnitario = document.getElementsByClassName('valor_unitario')[indice]
  let quantidade = document.getElementsByClassName('qnt')[indice]
  let tt = document.getElementsByClassName('total')[indice]
  
  preco.push(valorUnitario.value)
  qtd.push(quantidade.value)
  
  let total_simple = preco[indice] * qtd[indice]
   
  tt.value = total_simple
}
<table border = '2'>
            <thead>
                <tr>
                    <th>Preço</th>
                    <th>Quantidade</th>
                    <th>Total</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><input type="text" name="valor_unitario[]" class="valor_unitario" value="2.50" special="price" /></td>
                    <td><input type="text" name="qnt[]" class="qnt" value="1" special="quantity" /></td>
                    <td> <input type="text" name="total" class="total" readonly="readonly" onclick="calc(0, this);" /> </td>
                    
                </tr>
                <tr>
                    <td><input type="text" name="valor_unitario[]" class="valor_unitario" value="5.50" special="price" /></td>
                    <td><input type="text" name="qnt[]" class="qnt" value="1" special="quantity" /></td>
                    <td> <input type="text" name="total" class="total" readonly="readonly" onclick="calc(1, this);" /> </td>
                </tr>
                <tr>
                    <td><input type="text" name="valor_unitario[]" class="valor_unitario" value="1.20" special="price" /></td>
                    <td><input type="text" name="qnt[]" class="qnt" value="1" special="quantity" /></td>
                    <td> <input type="text" name="total" class="total" readonly="readonly" onclick="calc(2, this);" /> </td>
                </tr>
                <tr>
                    <td><input type="text" name="valor_unitario[]" class="valor_unitario" value="9.80" special="price" /></td> 
                    <td><input type="text" name="qnt[]" class="qnt" value="1" special="quantity" /></td>
                    <td> <input type="text" name="total" class="total" readonly="readonly" onclick="calc(3, this);" /> </td>
                </tr>                      
            </tbody>
            
        </table>
    
26.04.2018 / 20:29