Rayudu
Rayudu

Reputation: 1816

Generate table code( not table) based on input value (HTML, JavaScript)

I want to generate table code based on two input fields. One input field contains number of rows and another one contains number of columns. There is one more button called submit on click of that I need to generate table code for no of rows / no of columns.

Suppose If gave rows 3 and column 2, then it should generate code like

 <table>
       <tbody>
         <tr>
             <td>&nbsp;</td><td>&nbsp;</td>
         </tr>
         <tr>
             <td>&nbsp;</td><td>&nbsp;</td>
         </tr>
         <tr>
             <td>&nbsp;</td><td>&nbsp;</td>
         </tr>
       </tbody>
    </table>

This code I need to save into one string.

Please help me how to do this. I am beginner for JavaScript.

Upvotes: 0

Views: 1923

Answers (2)

Salmin Skenderovic
Salmin Skenderovic

Reputation: 1720

I made an example for you here: JS-FIDDLE

function buildTable() {
    var rows = document.getElementById("setRows").value;
    var cols = document.getElementById("setCols").value;
    var table = "<table>";
    table += "<tbody>";
    for (i=0;i<rows;i++) {
        table += "<tr>";
            for (j=0;j<cols;j++) {
                table += "<td>&nbsp;</td>";
            }
        table += "</tr>";   
    }
    table += "</tbody>";
    table += "</table>";
    document.getElementById("tableHolder").innerHTML=table;
}

Upvotes: 2

guest271314
guest271314

Reputation: 1

need to save into one string.

var form = document.getElementsByTagName("form")[0];
form["button"].onclick = function() {
  var html = "<table><tbody>";
  for (var i = 0; i < form["rows"].value; i++) {
    html += "<tr>";
    for (var j = 0; j < form["columns"].value; j++) {
      html += "<td>&nbsp;</td>"
    }
    html += "</tr>"
  }
  html += "</tbody></table>";
 
  console.log(html)
}
<form>
  <input type="number" min="1" max="10" name="rows" required />rows
  <input type="number" min="1" max="10" name="columns" required />columns
  <input type="button" name="button" value="create table" />
</form>

Upvotes: 2

Related Questions