David.Prifti David.Prifti - 3 months ago 61
jQuery Question

How to create a JavaScript Multiplication Table?

I am trying so hard to create a multiplication table that shows the results inside table cells and it generates a new table whenever you type a new number in the prompt dialog box. So far I have created the first row and the first colon. I have tried different ways to do the multiplication, but it does not work for me. Can you help me? (Down here you have the HTML, CSS and JS code.)



jQuery(document).ready(function() {

while (true) {

var $Number = prompt("Choose a number to create the Multiplication Table:");
if ($Number === '' + parseInt($Number)) {
break;
} else {
alert("You didn't type a number! Please type a number!");
}

}

for (var a = 1; a < parseInt($Number) + 1; a++) {
var cell = $("<td>" + a + "</td>");
$("#row1").append(cell); //Krijon rreshtin e pare me numrat nga 1 deri ne $Number

var colon = $("<tr> <td>" + a + "</t> </tr>").attr("class", a);
$("table").append(colon); //Krijon kolonen e pare me numrat nga 1 deri ne $Number

}

})

body {
max-width: 90%;
font-family: 'Open Sans', sans-serif;
margin: 0 auto;
}
h1 {
text-align: center;
margin-bottom: 1.5em;
}
table {
text-align: center;
margin-left: 2em;
margin-top: 1em;
}
td {
padding: 1em;
}

<!DOCTYPE html>
<html>

<head>
<link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="app.js"></script>
<link rel="stylesheet" type="text/css" href="main.css">
</head>

<body>

<h1> Multiplication Table </h1>

<table border="1">
<tr id="row1">
<td>X</td>
</tr>

</table>

</body>

</html>




Answer

You can try something like this:

Logic

Table is divided into 3 parts,

  • top panel: "X" followed by numbers
  • left panel: numbers only
  • body: multiplication values.

JSFiddle

function createBody(num) {
  var _html = "";
  for (var r = 0; r < num;) {
    _html += "<tr>";
    _html += "<td>" + ++r + "</td>";
    for (var c = 1; c <= num; c++) {
      _html += "<td>" + r * c + "</td>";
    }
    _html += "</tr>";
  }
  return _html;
}

function createHeader(num) {
  var _html = "<tr>";
  _html += "<td>X</td>";
  for (var r = 1; r <= num; r++) {
    _html += "<td>" + r + "</td>";
  }
  _html += "</tr>";
  return _html
}

(function() {
  var n = window.prompt("Enter a number");
  var html = createHeader(n) + createBody(n);
  document.getElementById("content").innerHTML = html
})()
table {
  text-align: center;
  margin-left: 2em;
  margin-top: 1em;
}
td {
  padding: 1em;
  border: 1px solid #ddd
}
<table id="content"></table>

Note: Its a bad practice to append elements in loop. You should create html string and perform a bulk operation.