Home » Javascript » Adding table rows and column dynamically with jQuery

Adding table rows and column dynamically with jQuery

Posted by: admin August 19, 2018 Leave a comment

Questions:

I’m trying to add rows and columns to a table using user input values to determine the number of rows and columns dynamically using jQuery. Below is my code which actually adds rows and columns but not according to the user’s inputs

function makeGrid() {
let numOfRow = 0; let numOfCol = 0;

$('#submit').on('click', function() {

    numOfRow = $('#height').val();
    numOfCol = $('#width').val();

    for (var i = 1; i <= numOfRow; i++) {
        let row = $('.grid-canvas').append('<tr>');
        for (col = 1; col <= numOfCol; col++) {
            $('tr').append('<td></td>');
        }
    }
}); 
}

makeGrid();

Assuming a user inputs numOfRow = 2 and numOfCol = 2, I should have a table like this

<tbody class="grid-canvas">
<tr>
    <td></td>
    <td></td>
</tr>
<tr>
    <td></td>
    <td></td>
</tr>

Problem is my code seems to be adding extra but I haven’t been able to figure it out. This is the result of my code

<tbody class="grid-canvas">
<tr>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
</tr>
<tr>
    <td></td>
    <td></td>
</tr>
</tbody>

How do I fix my code?

Answers: