I am trying to generate multiplication tables in JavaScript and pass the values to the rows of a table in html. I want an output like the image shown. Can anyone help me with this. I'm new to Javascript and am trying to figure out some of the basics. Thanks.

<html>
<head>
<title>Multiplication Table Generator</title>
<script language="javascript" type="text/javascript">
function generateTable()
{
var myVar = prompt("A number?", "");
var myVar = multTables.number.value;
var myString = "";
for (i=1; i<=myVar; i++) {
myString += i+ " x " +myVar+ " = " +(i*myVar)+ "\n";
}
}
</script>
</head>
<body>
<h1>Times Tables</h1>
<form name="multTables">
Enter a number<input type=text name="number">
<input type=button name="button1" value="Show Table" onclick="generateTable()">
<table border=1>
<tr><th>times tables</th></tr>
<tr><td>
<!-- 1X7, 2X7...etc-->
</td>
<td>
<!-- 7, 14, 21...etc-->
</td>
</tr>
</table>
</form>
</body>
</html>
I don't understand why you are using html form and js prompt at the same time.
Ok, you can use this :
<html>
<head>
<title>Multiplication Table Generator</title>
<script language="javascript" type="text/javascript">
function generateTable()
{
//var myVar = prompt("A number?", "");
var myVar = document.forms.multTables.x.value;
var myString = "<tr><th>"+ myVar + " times tables</th></tr>";
for (i=1; i<=myVar; i++)
{
myString += "<tr><td>";
myString += i+ " x " +myVar+ " = " +(i*myVar)+ "\n";
myString += "</td></tr>";
}
document.getElementById('t').innerHTML = myString;
return false;
}
</script>
</head>
<body>
<h1>Times Tables</h1>
<form name="multTables">
Enter a number<input type="text" name="number" id="x">
<input type="button" name="button1" value="Show Table" onclick="generateTable()">
<table border="1" id="t">
</table>
</form>
</body>
</html>
Okay so I set up a small example here that should give you a nice example of how to do this:
http://jsfiddle.net/MHfyE/
HTML:
<div id="content">
</div>
<button id="button">Do It!</button>
Javascript:
var buttonElt = document.getElementById("button");
buttonElt.onclick = function() {
var elt = document.createElement("div");
for (var i = 0; i < 10; i++) {
var childElt = document.createElement("p");
childElt.innerHTML = i;
elt.appendChild(childElt);
}
var parentElt = document.getElementById("content");
parentElt.appendChild(elt);
}
I feel like this is enough to get you started.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With