Enter numbers and print them in JavaScript



I want to make a box for entering a number by the user, and doing simple arithmetic operations on it, and printing the result through a table, consisting of fixed numbers and variables that are the result of the arithmetic operations on it. I made the variables to receive the value and make the calculations, and I prepared a matrix containing the fixed numbers with the variables being put in their places.

function generate_table() {
  var table = document.createElement('table');
  var x = document.getElementById("num").Value
  var y = x - 20;
  for (var i = 0; i < 4; i++) {
    var tr = document.createElement('tr');

    var t1 = [8, (y - 1), 3, 10]
    var t2 = [11, 2, (y + 2), 5]
    var t3 = [y, 7, 9, 4]
    var t4 = [1, 12, 6, (y + 1)]


    var td1 = document.createElement('td');
    var td2 = document.createElement('td');
    var td3 = document.createElement('td');
    var td4 = document.createElement('td');

    var text1 = document.createTextNode(t1[i]);
    var text2 = document.createTextNode(t2[i]);
    var text3 = document.createTextNode(t3[i]);
    var text4 = document.createTextNode(t4[i]);

    td1.appendChild(text1);
    td2.appendChild(text2);
    td3.appendChild(text3);
    td4.appendChild(text4);
    tr.appendChild(td1);
    tr.appendChild(td2);
    tr.appendChild(td3);
    tr.appendChild(td4);

    table.appendChild(tr);
  }
<input type="number" id="num">
<input type="button" value="Generate a table." onclick="generate_table()">

The problem is that the table comes out without the variable values

enter image description here

I tried to add a form between the button and the input and the result is the same.

And I want to add a condition if the entry is not entered, it is not printed, and after the entry, the modification is prohibited.

Answer

First, make sure that you change your .Value to .value like this:

var x = document.getElementById("num").value;

Also, since the value you’re getting from the input box is of type string you have to parse it into a number!

Here are some examples how you can do that:

// During the variable declaration:
var x = Number.parseInt(document.getElementById("num").value);
// Or
var x = +document.getElementById("num").value;
// Or
var x = parseInt(document.getElementById("num").value;

In my own opinion the best way is to use the Number object an its parseInt method, that makes it way more readable than using a simple + character!

Have a good day!



Source: stackoverflow