Akhil Anand
Akhil Anand

Reputation: 47

Print Multiplication table values into a text-box in JavaScript

I have used the below script for printing multiplication table of 9 but it is not working as expected as the loop which I defined is not proper. Please help on this

document.write("<table border='2' width='30%'>");
document.write("<tr><th>X</th><th>Y</th><th>X*Y</th></tr>");
for (i = 1; i <= 10; i++) {
  document.write("<tr><td>" + i + "</td>" + "<td>9</td>" + "<td><input type='text' id='sum'></td></tr>");
  var x = i * 9;
  document.getElementById("sum").value = x;
}
document.write("</table>");
<form>
</form>

Upvotes: 0

Views: 1072

Answers (4)

Ravindra Kumar
Ravindra Kumar

Reputation: 1950

I slightly change your code and I got this:-

document.write("<table border='2' width='30%'>");
    			 document.write("<tr><th>X</th><th>Y</th><th>X*Y</th></tr>");
    			 for(i=1;i<=10;i++)
    			 {
    			 document.write("<tr><td>"+i+"</td>"+"<td>9</td>"+"<td><input type='text' id='sum' value=" + i*9+ "></td></tr>");
    			 
    			 }
    			 document.write("</table>");
  

   

Upvotes: 0

Vladimir Proskurin
Vladimir Proskurin

Reputation: 391

Id Must be unique, you also use the same. Just paste X into a string with html

document.write("<table border='2' width='30%'>");
document.write("<tr><th>X</th><th>Y</th><th>X*Y</th></tr>");
for (i = 1; i <= 10; i++) {
    var x = i * 9;
  document.write("<tr><td>" + i + "</td>" + "<td>9</td>" + "<td><input type='text' value=\"" + x + "\"></td></tr>");

}
document.write("</table>");

Upvotes: 0

Alexander Arce
Alexander Arce

Reputation: 126

You need to add the i value to the sum div like this:

   <html><head>
 <form>
 <script language="JavaScript">
 document.write("<table border='2' width='30%'>");
 document.write("<tr><th>X</th><th>Y</th><th>X*Y</th></tr>");
 for(i=1;i<=10;i++)
 {
 document.write("<tr><td>"+i+"</td>"+"<td>9</td>"+"<td><input type='text' id='sum" + i +"'></td></tr>");
 var x=i*9;
 document.getElementById("sum" + i).value=x;
 }
 document.write("</table>");
</script>
</head><body>
</body>
</html>  

Upvotes: 2

Beginner
Beginner

Reputation: 9125

i hope this will work .. happy coding :)

$(document).ready(() => {
  let html = [];
 
  for(let i =1; i<=10 ; i++){
     html.push(`<tr> 
                  <td>9 * ${i}</td>
                  <td>= ${9 * i}</td>
                </tr>`)
  }
  $("#mulNine").append(html.join(""))
  
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table id ="mulNine"></table>

Upvotes: 0

Related Questions