Click here to Skip to main content
15,881,757 members
Articles / Programming Languages / Javascript
Tip/Trick

HTML Table Inline Edit - Part Two

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
8 Apr 2015CPOL 8.4K   7  
Part two of HTML table inline edit

Introduction

In Part one of this article, I present a simple implementation of Gridview style inline editing by jQuery. In Part two of this article, I am going to show an editor style HTML table inline editing by jQuery.

Using the Code

This editor style HTML table works like this. If a table cell is editable, its background color changes to light blue when mouseover. Double click a table cell to convert its text to textbox for editing. When editing in the textbox, press Enter key to commit the change. Press Escape key to cancel the change.

First, add the following HTML markup to a web page.

HTML
<div>
    <div class="errorSummary"></div>
    <table id="tblCats" class="simpleTable">
        <tr>
            <th>Category Id</th>
            <th>Category Name</th>
            <th>Short Description</th>
        </tr>
    </table>
</div>

Second, add a JavaScript global object to serve as table data source.

JavaScript
// Create a global variable by module pattern
var catObj = (function () {
    // Private variables
    var cat = [];
    var maxCatId = 0;
    // Return object
    return {
        // Public method to get array cat
        GetCats: function () {
            return cat;
        },
        // Public method to add an item to array cat
        AddCat: function (cat_name, short_desc) {
            var cat_id = ++maxCatId;
            cat.push({ cat_id: cat_id, cat_name: cat_name, short_desc: short_desc });
        },
        // Public method to update cat_name of an item in array cat
        UpdateCatName: function (cat_id, cat_name) {
            for (var i = 0; i < cat.length; i++) {
                if (cat[i].cat_id == cat_id) {
                    cat[i].cat_name = cat_name;
                    break;
                }
            }
        },
        // Public method to update short_desc of an item in array cat
        UpdateShortDesc: function (cat_id, short_desc) {
            for (var i = 0; i < cat.length; i++) {
                if (cat[i].cat_id == cat_id) {
                    cat[i].short_desc = short_desc;
                    break;
                }
            }
        }
    };
})();

Last, add some jQuery code to do inline editing.

JavaScript
$(document).ready(function () {
    // Initialize object catObj
    catObj.AddCat('cat name 1', 'short desc 1');
    catObj.AddCat('cat name 2', 'short desc 2');
    catObj.AddCat('cat name 3', 'short desc 3');
    catObj.AddCat('cat name 4', 'short desc 4');
    catObj.AddCat('cat name 5', 'short desc 5');
    catObj.AddCat('cat name 6', 'short desc 6');
    // Populate table with data from object catObj
    PopulateTable(catObj.GetCats());
});

// Table inline editing function
// Parameters: thisCell - this td element, colNum - td index
function DoEdit(thisCell, colNum) {
    var catId;
    var catName;
    var shortDesc;
    // if the table cell is not in edit mode
    if ($(thisCell).find('input').length == 0) {
        if (colNum == 1) {
            // Edit Category Name
            catName = $(thisCell).html();
            $(thisCell).html('<input type="text" data-oldvalue="' + catName + '" />');
            $(thisCell).find('input').val(catName);
            $(thisCell).find('input').trigger('focus');
            $(thisCell).find('input').keypress(function (e) {
                if (e.which == 13) {
                    // If Enter key is pressed, update data.
                    catName = $(this).val();
                    catId = $(this).parent().parent().find('td:first').html();
                    if (catName == '') {
                        $('div.errorSummary').html('Category Name cannot be empty!');
                        $('div.errorSummary').show();
                    } else {
                        catObj.UpdateCatName(catId, catName);
                        PopulateTable(catObj.GetCats());
                    }
                } else if (e.which == 27) {
                    // If Escape key is pressed, cancel update.
                    catName = $(this).attr('data-oldvalue');
                    $(this).parent().html(catName);
                }
            });
        } else if (colNum == 2) {
            // Edit Short Description
            shortDesc = $(thisCell).html();
            $(thisCell).html('<input type="text" data-oldvalue="' + shortDesc + '" />');
            $(thisCell).find('input').val(shortDesc);
            $(thisCell).find('input').trigger('focus');
            $(thisCell).find('input').keypress(function (e) {
                if (e.which == 13) {
                    // If Enter key is pressed, update data.
                    shortDesc = $(this).val();
                    catId = $(this).parent().parent().find('td:first').html();
                    if (shortDesc == '') {
                        $('div.errorSummary').html('Short Description cannot be empty!');
                        $('div.errorSummary').show();
                    } else {
                        catObj.UpdateShortDesc(catId, shortDesc);
                        PopulateTable(catObj.GetCats());
                    }
                } else if (e.which == 27) {
                    // If Escape key is pressed, cancel update.
                    shortDesc = $(this).attr('data-oldvalue');
                    $(this).parent().html(shortDesc);
                }
            });
        }
    }
}

function PopulateTable(data) {
    // Hide error summary section
    $('div.errorSummary').hide();
    $('#tblCats tr:gt(0)').remove();
    // Populate table with data source from function parameter
    $(data).each(function () {
        var row = '<tr><td>' + this.cat_id + '</td><td>' +
                this.cat_name + '</td><td>' + this.short_desc + '</td></tr>'
        $('#tblCats').append(row);
    });
    $('#tblCats tr:gt(0)').each(function () {
        // Highlight editable cells when mouseover
        $(this).find('td:gt(0)').hover(
            function () {
                $(this).css('background-color', '#87CEFA');
                $(this).css('cursor', 'pointer');
            },
            function () {
                $(this).css('background-color', '');
                $(this).css('cursor', 'auto');
            }
        );
        // Double-click to edit table cell.
        $(this).find('td:eq(1)').dblclick(function () {
            DoEdit(this, 1);
        });
        $(this).find('td:eq(2)').dblclick(function () {
            DoEdit(this, 2);
        });
    });
}

In this article, the data source is a JavaScript global object. If the data source is a server side database table, Ajax calls or form post request can be used to work with server side data source.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Canada Canada
I am working with ASP.NET related technologies.

Comments and Discussions

 
-- There are no messages in this forum --