Javascript calculation and play in html table

Asked

Viewed 1,951 times

1

I have an html table of 3 columns, the first 2 are <input type="number"> and the third is text.

I want to play in the third the sum of the values of inputs using the onchange, but what I’m facing is that if I put "2" on each input, the sum in the third column is 6 as the previous value of the input influences the final result.

How do I solve this problem??

Below my code.

<table>
  <tr>
    <td>valor 1</td>
    <td>valor 2</td>
    <td>total</td>
  </tr>
  <tr>
    <td><input type="number" min="0" onchange="calcula(this.value)"></td>
    <td><input type="number" min="0" onchange="calcula(this.value)"></td>
    <td><input type="text" readonly value="0" id="teste"></td>
  </tr>
</table>

<script type="text/javascript">
  function calcula(valor){
    var soma = parseInt(document.getElementById("teste").value);
    soma += parseInt(valor);
    document.getElementById("teste").value = soma;
}
</script>

1 answer

3


If the third input is the sum of the others it makes no sense to add up including the total that is what it does:

var soma = parseInt(document.getElementById("teste").value);

I suggest you remove that and go to the DOM and look for all the elements:

function calcula() {
    var inputs = document.querySelectorAll('input[type="number"]');
    var soma = 0;
    for (var i = 0; i < inputs.length; i++) {
        soma += parseInt(inputs[i].value) || 0;
        document.getElementById("teste").value = soma;
    }
}

jsFiddle: http://jsfiddle.net/x30n7rvg/

Another way, which I prefer by separating JS from HTML, and saving global functions is:

(function () {
    var inputs = [].map.call(document.querySelectorAll('table tr input[type="number"]'), function (input) {
        input.addEventListener('change', calcula);
        return input;
    });

    function calcula() {
        var soma = inputs.reduce(function (soma, input) {
            var nr = parseInt(input.value) || 0;
            return soma + nr;
        }, 0);
        document.getElementById("teste").value = soma;
    }
})();

jsFiddle: http://jsfiddle.net/38sway5d/

In this last example the code goes to the DOM to fetch the inputs when the page loads and then works from the memory to iterate the elements.

I used [].map.call() to convert the input list into an array and then use the reduce what perfect for these summation case.

Look what I used var nr = parseInt(input.value) || 0; to tell 0 if the input has no value.

  • 1

    Thanks for the tips. I will try to use and, if necessary, adapt to a dynamic table I have.

Browser other questions tagged

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