0

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.

Rayudu
  • 1,806
  • 1
  • 14
  • 31
  • Also http://stackoverflow.com/questions/11563638/javascript-get-input-text-value will help – Satpal Nov 10 '15 at 07:28
  • 1
    @Satpal: Mine is **generate table code** based on inputs. Not generate table. Please have a look. – Rayudu Nov 10 '15 at 07:41
  • 1
    http://stackoverflow.com/a/14643642 is a good reference to generate table. You should have used the posts to __learn__ and generate table. – Satpal Nov 10 '15 at 08:18

2 Answers2

2

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>
guest271314
  • 1
  • 15
  • 104
  • 177
2

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;
}
Salmin Skenderovic
  • 1,750
  • 9
  • 22