The question is published on by Tutorial Guruji team.
im wondering why my function isn’t outputting to my table when i change the variable “n” through its text box.
I’ve never tried this before… And I’m thinking the cause might be because i’m trying to use a loop within a function and may also have syntax erros.
<label>N:</label> <br> <input id="N" type="number" onchange="fraccsum()" value=1> <br> <table> <tr> <td>N </td> <td>fractions in decimal form</td> </tr> <script> // function pulls N value and displays on the table function fraccsum() { // Pulls N Value var N = document.getElementById("N").value; var Sum=0; // my formula to find the sum of the fraction for (var fraction = 1; fraction <= N; fraction++) { ThisN = 1/fraction; Sum = Sum + ThisN; //this writes down all the answers document.write("<tr><td>"+ fraction +"</td>"); document.write("<td>" + "" + ThisN +"</td></tr>"); } document.write("<tr><td>" + "Total:" + Sum +"</td></tr>"); </script>
Answer
First I get a error on the variable “sum”, you have it in both uppercase and lowercase (Sum & sum). So choose one and stick to it.
Second you didn’t close off the function fraccsum.
Third you shouldn’t use document.write since its bad practice. I got the code rendered hope this helps.
<label>N:</label> <br> <input id="N" type="number" onchange="fraccsum()" value=1> <br> <table> <tr> <td>N </td> <td>fractions in decimal form</td> </tr> </table> <!-- Add a placeholder for the tavle --> <table id="placeholderTable"></table> <script> // function pulls N value and displays on the table function fraccsum() { // Pulls N Value var N = document.getElementById("N").value; var placeholder = document.getElementById("placeholderTable"); var sum=0; var renderHtml = ""; // my formula to find the sum of the fraction for (var fraction = 1; fraction <= N; fraction++) { ThisN = 1/fraction; sum = sum + ThisN; //this writes down all the answers renderHtml += "<tr><td>"+ fraction +"</td>" + "<td>" + "" + ThisN +"</td></tr>"; // document.write("<tr><td>"+ fraction +"</td>"); // console.log(fraction); // document.write("<td>" + "" + ThisN +"</td></tr>"); } renderHtml += "<tr><td>" + "Total:" + sum +"</td></tr>"; placeholder.innerHTML = renderHtml; // document.write("<tr><td>" + "Total:" + sum +"</td></tr>"); } </script>
Also even though I didn’t include it in your code i would suggest you have a look at template literals, makes for cleaner code in my opinion. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals