Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to create an editable HTML table with jQuery

See in this article how to make an HTML table editable using jQuery, to allow the user to change cell values ​​directly, without the need for auxiliary forms.

Introduction

The display data in the table is one of the most common ways to be found in commercial systems, regardless of the market segment. The tables or grids possess a fundamental role in applications that need an organized list of data (rows and columns).

On most screens query uses one (or more) table (s) to display the search result for the user, where it can sometimes select rows records and perform operations such as editing and deleting records.

However, there are situations where you may want to allow the user to edit data directly in the table by changing the value of each cell without having to use another page or a separate form. In order to satisfy such situations, this article presents a simple solution and easy implementation of the functionality of editing HTML tables using the jQuery library.

The HTML code

The structure of the HTML page used is very simple, consisting only of a table with three rows (besides the header). The code listing below can be copied and saved as HTML.

Listing 1: HTML code used for example

<!DOCTYPE html> 
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>How to become an editable HTML table with jQuery - MrBool Tutorial</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
    <script type="text/javascript" src="script.js"></script>
</head>
<body>
    <table class="editableTable">
        <thead>
            <tr>
                <th>Code</th>
                <th>Name</th>
                <th>Email</th>
                <th>Phone</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>001</td>
                <td>Pedro Augusto</td>
                <td>pedro.augusto@myemail.com</td>
                <td>(21) 9999-8888</td>
            </tr>
            <tr>
                <td>002</td>
                <td>Paula Silva</td>
                <td>paula.silva@mymail.com</td>
                <td>(81) 8787-8686</td>
            </tr>
            <tr>
                <td>003</td>
                <td>Lucas Costa</td>
                <td>lucas.costa@myemail.com</td>
                <td>(84) 3232-3232</td>
            </tr>
        </tbody>
    </table>
</body>
</html>

In the page header (head tag) were references to the following files:

style.css: CSS file containing some basic formatting for improving the appearance of the page and to facilitate visualization of the working example. The contents of this file is shown in the listing 2.

http://code.jquery.com/jquery-1.8.3.min.js: jQuery library needed to implement the functionality in question. Without it, the Javascript code used would be much more extensive and complex. In this example we used the file hosted on the official website, could be used a local file (by downloading this link, for instance), simply change the path of the reference.

script.js: Javascript file which contained the code that will give you the desired functionality to the table. The contents of this file is shown below.

Improving the appearance of the page

Just to give a better appearance to the page and make the data more visible, will be applied a stylesheet basic (file style.css), as the following code.

Listing 2: Content of style.css

* {
    font-family:Consolas
}
 
.editableTable {
    border:solid 1px;
    width:100%
}
 
.editableTable td {
    border:solid 1px;
}
 
.editableTable .cellEditing {
    padding: 0;
}
 
.editableTable .cellEditing input[type=text]{
    width:100%;
    border:0;
    background-color:rgb(255,253,210);  
}

In addition to formatting the the table was set a specific class, the class "cellEditing." It defines some details to the table cell, when it is being edited. This class will be used later in the Javascript code and it will be added and removed from the td tags when user edit cell text.

After applying this stylesheet, opening the HTML file in the browser, you should get the following result:

Page opened in the browser

Figure 1: Page opened in the browser

The code Javascript / jQuery

The editing process will work as follows: the user must give two clicks on the cell you want to edit, enter the new value and press Enter to finish editing.

So all will occur in event of dblclick function of td tags, or table cell. The following is the contents of the file script.js, as we see is very simple.

Listing 3: script.js content

$(function () {
    $("td").dblclick(function () {
        var OriginalContent = $(this).text();
         
        $(this).addClass("cellEditing");
        $(this).html("<input type='text' value='" + OriginalContent + "' />");
        $(this).children().first().focus();
 
        $(this).children().first().keypress(function (e) {
            if (e.which == 13) {
                var newContent = $(this).val();
                $(this).parent().text(newContent);
                $(this).parent().removeClass("cellEditing");
            }
        });
         
    $(this).children().first().blur(function(){
        $(this).parent().text(OriginalContent);
        $(this).parent().removeClass("cellEditing");
    });
    });
});

The explanation of each line of code above is given below:

  • Lines 1 and 22: opening and closing the main function that handles the event ready of the document. Everything that needs to occur when the page loads should be in the body of this function.
  • Lines 2 and 21: opening and closing of the function that handles the event dblclick td tags. The processing of the edition is inside this function.
  • Line 3: Obtain and record the value in the cell being edited. This value will be used later.
  • Line 5: Addition of class cellEditing the cell in which the user has double-clicked.
  • Line 6: Inserting an input in the cell containing the value that was originally on this.
  • Line 7: directing the focus (cursor) to the input that was just created, so that the user does not need to click on it again.
  • Lines 9 and 15: the opening and closing function that handles the keypress event of the input. A reserved word this refers to the cell that was clicked. We use the functions first and children to get the first child element of the cell, ie the input.
  • Lines 10 and 14: opening and closing of the IF operator to check if the pressed key is the Enter key. If so, executes lines 11 to 13.
  • Line 11: stores in newContent variable, the value entered by the user in the input, then put in the cell for the new value. This line and the two following the reserved word this refers to the input, but not the td tag.
  • Line 12: the cell puts the new value entered in the input, using the text function of jQuery that gets or changes (in this case) the text of an element. In this line function was used to capture the parent cell (td tag containing the input) since the instruction lies within an input function itself and not more than td.
  • Line 13: remove the class cellEditing of the cell that has just been published.
  • Lines 17 and 20: the opening and closing of the function that handles the event blur (when the element loses focus) the input. It will be used to return the original value of the cell, if the user exits the input without pressing Enter.
  • Line 18: again using the text function, cell text back to the original content.
  • Line 19: remove the class cellEditing of the cell that has just been published.

Having understood the workings of the code, you can reopen the file in the browser (or update, if you were already open) and check the running example, as illustrated in the figure below.

Table with cell editing

Figure 2: Table with cell editing

 Table with edited cell

Figure 3: Table with edited cell

Conclusion

In this article was presented a proposed code simple, easy to implement and understanding to allow the user to edit the cell contents of an HTML table directly in the table, without a form helper.

We used the jQuery library, which ensures a much simpler code than would be necessary if they were used only the native capabilities of the JavaScript language.

You can download the source code at the beginning of this article and test the code in your own application.

The comments section below is open for questions, comments or opinions about the article in general.



Microsoft MVP, Bachelor in Science And Technology, Editor and Consultant at DevMedia with more than 7 years of experience in software development.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login