Calculate the total of each row in the table

Asked

Viewed 191 times

0

I’m trying to use Javascript to dynamically calculate my prices multiplied by the quantities and result in the total for each row, however it calculates the overall total and plays in the last field of the Total column. As in the picture below:

inserir a descrição da imagem aqui

    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>

  • 1

    I saw it, quiet!

2 answers

1

You can simplify by 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>

  • 1

    I will fix some details, currently is bug, I already update the code

  • would it be possible to change the event to pick up dynamically when it came out with the focus of quantity input ? I used onkeyup, onblur, onclick, but none takes dynamically without the focus going through the total input

  • @Victor I’ll make a better example the way you want

1


Do not use equal ids

Just change the input values you automatically calculate.

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 cannot have the same identification. You can select an element based on this unique identification with the getElementById() method of the Document object.

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 starts exactly with a given string (valor_unitario). Could also be valor_

Attribute Starts With Selector [name ="value"]

  • I am bringing an array from the bank so I believe I will have no problem as to the ids

  • @Victor, I understand, each page can have only one element with that ID, plus your code will not go through the validator if you use the same ID in more than one element.

  • I tried to use your example but I could not, when copying and pasting it does not work here, how strange

  • @Victor, in the Run my answer works, so you must have got something wrong.

  • i copied and pasted it like I said, and when I open the console error this line printSum.textContent = total.toFixed(2); "Uncaught Type Error Cannot set Property 'textContent' of null"

  • @Victor maybe pasted javascript before html. Put it after html.

  • now it worked, thanks man, know if I can do it with a while and variable incrementer ?

  • 1

    @Victor changes this question even by clicking edit, and put the part of PHP that contains the while

  • I managed to do, thank you for making yourself available

  • @See working, enter values in the table with the form http://kithomepage.com/sos/blabla.php

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.