Building Tables Dynamically

by Joe Saad

HTML

<label for="colNum">
    How many columns you want to have?
    <input type="text" id="colNum"/>
</label>

<div id="supply">
    <table>
    <thead>
        <tr>
        </tr>
    </thead>
    <tbody>
        <tr>
        </tr>
    </tbody>
</table>
    
</div>

CSS

table, tr, td, th {border-collapse: collapse; border: 1px solid #000;}

table {width: 100%;}
th, td {height: 20px;}

JavaScript

$('#colNum').focus();

$('#colNum').keypress(function(e){
    if (e.keyCode === 13) {
        drawTable($(this).val());
    }
});

function drawTable(col){
    for (var i = 0; i< col; i++){
        $('#supply table thead tr').append("<th></th>");
        $('#supply table tbody tr').append("<td></td>");
    }
}

$('table').on('click','th, td',function(){
    if ($(this).find('input').length === 0) {
        $(this).html('<input />');
        $(this).find('input').focus();
    }
});

$('table').on('keypress','th input, td input', function(e){
    var newCellVal;
    if ((e.keyCode ===13 ) || (e.keyCode ===9) ) {
      newCellVal = $(this).val();
      $(this).closest('th,td').next('th,td').trigger('click');
      $(this).closest('th,td').html(newCellVal);
    }
});

$('table').on('keypress','td:last-child input', function(e){
    if ((e.keyCode ===13 ) || (e.keyCode ===9) ) {
        $('tbody').append('<tr></tr>');
        for (var i=0; i< $('#colNum').val(); i++)
            $('tbody tr:last-child').append('<td></td>');
    }
});