Home > database >  How to make a row in a table with the sum of all the numbers in a column? Javascript beginner
How to make a row in a table with the sum of all the numbers in a column? Javascript beginner

Time:06-05

Without further due, this is my problem: The created table is basically a form that takes a number in a loop and it calculates that number squared and factorial of it. I have managed to do that successfully but next problem Im encountering is I need to add sum of elements at the bottom of the table for all three columns. Much appreciated.

<script>
        function tablica() {
            var nr = document.getElementById("broj").value
            if (nr < 2) {
                document.getElementById("rezultat").innerHTML = "Prilagođeno samo za rad s brojevima većim od 1";
                window.alert("Unijeli ste broj "   broj.value   ", a taj broj je manji od 2...");
            } else if (nr >= 2) {
                var rez = "<table id='tablica'><tr><th>N</th><th>N²</th><th>N!</th></tr>";
                var faktorijela = 1;
            }
            for (var i = 1; i <= nr; i  ) {
                rez = rez   "<tr><td>"   i   "</td><td>"   i * i   "</td><td>"   (faktorijela = faktorijela * i)   "</td></tr>";
            }
            rez = rez   "</table>"

            var rezTablica = document.getElementById("rezultat");
            rezTablica.innerHTML = rez;
        }
    </script>

CodePudding user response:

I have created variables sum1, sum2 and sum3 to store each column's sum.

Please see snippet below :

function tablica() {
            var sum1 = 0, sum2 = 0, sum3 = 0;
            var nr = document.getElementById("broj").value
            if (nr < 2) {
                document.getElementById("rezultat").innerHTML = "Prilagođeno samo za rad s brojevima većim od 1";
                window.alert("Unijeli ste broj "   broj.value   ", a taj broj je manji od 2...");
            } else if (nr >= 2) {
                var rez = "<table id='tablica'><tr><th>N</th><th>N²</th><th>N!</th></tr>";
                var faktorijela = 1;
            }
            for (var i = 1; i <= nr; i  ) {
                let val1 = i;
                let val2 = i * i;
                let val3 = (faktorijela = faktorijela * i);
                rez = rez   "<tr><td>"   val1   "</td><td>"   val2   "</td><td>"   val3   "</td></tr>";
                sum1 = sum1   val1;
                sum2 = sum2   val2;
                sum3 = sum3   val3;
            }
            rez = rez   "<tr><td>"   sum1   "</td><td>"   sum2   "</td><td>"   sum3   "</td></tr>";
            rez = rez   "</table>"

            var rezTablica = document.getElementById("rezultat");
            rezTablica.innerHTML = rez;
        }
<input id="broj" type="text">
<button onclick="tablica()">Test</button>
<div id="rezultat">
</div>

  • Related