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.

3
  • Also stackoverflow.com/questions/11563638/… will help Commented Nov 10, 2015 at 7:28
  • 1
    @Satpal: Mine is generate table code based on inputs. Not generate table. Please have a look. Commented Nov 10, 2015 at 7:41
  • 1
    stackoverflow.com/a/14643642 is a good reference to generate table. You should have used the posts to learn and generate table. Commented Nov 10, 2015 at 8:18

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.