0

How could I make a dynamic table when the number of rows (number of <tr> tags) and number of columns (number of <td> tags) are entered by the user?

I also need to make sure that each <td>tag has a unique id.

HTML:

I have a <div id=tabel> ... </div> in my html code where I need to insert this dynamic table.

Javascript:

var rows = content.rows, colums = content.columns, size = colums * rows, i;
$("tabel").append("<table>");

for (i = 0; i < size; i += 1) { 

// make table with dynamic <tr> and <td>

} 

Pseudocode or snippets of code would help me a lot!

1
  • 1
    for (;r < rows;) {create TR to TABLE; for (;c < columns;) {create TD to TR}}. Commented May 10, 2016 at 16:47

1 Answer 1

1

You'll need a nested for loop. Loop the rows then inside each row loop the columns:

https://jsfiddle.net/g80hzjgn/2/

var rows, cols, domRow, domCol, 
  table = $('#table'), 
  cellId = 0;

jQuery('#submit').click(function(){
  table.empty();
  rows = parseInt($('#row-input').val());
  cols = parseInt($('#col-input').val());

  for(var i = 0; i < rows; i++){
    domRow = $('<tr/>');
    for(var x = 0; x < cols; x++){
      domCol = $('<td/>',{
        'id': "cell-" + cellId++,
        'text': 'cell'
      });
      domRow.append(domCol);
    }
    table.append(domRow);
  }
});
Sign up to request clarification or add additional context in comments.

3 Comments

Great! But I want to use jQuery selectors instead of doing it your way. @Matt Coady
Awesome! One last question: what if I want to insert images to the <td> tag? Image with <src=0.png> needs to be added to cell-0 and so on... If I want to do this in another function (so I could shuffle them) how would I approach this problem? @Matt Coady
After domCol is created (but before it gets appended to domRow) make an image element and append it to domCol: $('<img/>', {'src':'0.png'}).appendTo(domCol) You'll also want to remove the 'text':'cell' bit I added (and the comma on the previous line).

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.