Dynamic table

Dynamic table which has to be editable as well.

by Rohit Bisht

HTML

<label>Rows: <input type="text" name="rows" id="rows"/></label><br />
<label>Cols: <input type="text" name="cols" id="cols"/></label><br/>
<input name="generate" type="button" value="Create Table!" id='createit'/>
<div id="wrapper"></div>

CSS

.editableTable {
            border: solid 0px;
            width: 100%;
            text-align: center
        }

        .editableTable td {
            border: solid 0.5px;
            border-color: lightblue;
            min-width: 140px;
        }

        .editableTable .cellEditing {
            padding: 0;
        }

        select {
            border: 0px;
            width: 100%;
        }

JavaScript

$("#createit").click(function() {
    var num_rows = document.getElementById("rows").value;
    var num_cols = document.getElementById("cols").value;
    var tab_index=0;
    var theader = "<table class='editableTable'>";
    var tbody = "<tbody>";
    var temp = 0;
    for (var i = 0; i < num_rows; i++) {
        tbody += "<tr>";
        temp=i;
        for (var j = 0; j < num_cols; j++) {
            tbody += "<td tabindex=" + temp + ">";
            tbody += temp;
            tbody += "</td>";
            temp =  parseFloat(temp)+parseFloat(num_rows);
        }
        tbody += "</tr>";
    }
    var tfooter = "</tbody></table>";
    document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
    $("td").dblclick(function() {
        console.log('clicked');
        var OriginalContent = $(this).text();
        $(this).addClass("cellEditing");
        $(this).html("<select><option>1</option><option>2</option><option >3</option></select>");
        $(this).children().first().focus();
        $(this).bgColor = 'red';

        $(this).children().first().keypress(function(e) {
            if (e.which == 13) {
                var newContent = OriginalContent;
                $(this).parent().text(OriginalContent);
                $(this).parent().removeClass("cellEditing");
            }
        });
        $(this).children().first().blur(function() {
            $(this).parent().text(OriginalContent);
            $(this).parent().removeClass("cellEditing");
        });
    });

    $("td").bind('keydown', function(event) {
        if (event.keyCode === 9 || event.keyCode === 13) {
            var tabindex = $(this).attr('tabindex');
            tabindex++; //increment tabindex
            $('[tabindex=' + tabindex + ']').focus().dblclick();
            return false;
        }
    });
});