Create Editable HTML table using jQuery & JavaScript

This post is all about javascript and an editable HTML table. There are many operations we perform on an HTML table using Javascript. such as editable cells, adding rows, deleting rows, Drag and drop, Navigation, search, etc. This post will explain everything with demo and code.

How to add and remove rows and columns in a table using jQuery

This is a simple tutorial which shows how you can add or remove rows and columns on the fly using jQuery

1. Creating Editable cell in HTML table Using jquery

$(function () {
    $("td").dblclick(function () {
        var OriginalContent = $(this).text();

        $(this).addClass("cellEditing");
        $(this).html("
" + 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");
    });
    });
});

Demo: http://jsfiddle.net/ExA3j/8/

The above jQuery code will make the cell editable on the cell double-click. Add class to the table cell and put the above jQuery in the head. This jQuery makes the table editable o double-click. After editing the cell you can press enter key to change values. You can use Ajax to send the changes to the database.

Code for editable table using Ajax

$(this).children().first().keypress(function (e) {
	if (e.which == 13) {
		var fullContent = $(this).val();
	        $(this).parent().html(fullContent);
	        $(this).parent().removeClass("cellEditing");
	        //Call the server side file to communicate with database.
	        var URL = '/callfile.php' ;
	        //alert (URL);
	        var xmlhttp;    
	        if (window.XMLHttpRequest){
                        // code for IE7+, Firefox, Chrome, Opera, Safari
	        	xmlhttp=new XMLHttpRequest();
	        }
	        else{
                        // code for IE6, IE5
	        	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	        }
	        xmlhttp.onreadystatechange=function(){
                       // if successfully done it will return status 200
	        	if (xmlhttp.readyState==4 && xmlhttp.status!=200){
	        		alert ('Can not update comment. Contact admin')
	        	}

	       }
	        xmlhttp.open("GET",URL,true);
	        xmlhttp.send();
	}
});

Add / Delete rows in HTML table using Javascript

$('button').live('click' , function(event){
      var $row = (" 6  class6  school6  ");
      $('#example').append($row);
      });

There are scenarios where we have to add rows from one table to another and delete them in the first table. This example will show how we can add a row in one table from another table.

 

$('#example tbody tr td').live('click' , function(event){
      var $row = $(this).closest('tr');
      $(this).closest("tr").remove(); // remove row
      $('#example2').append($row);
      });

$('#example2 tbody tr td').live('click' , function(event){
      var $row = $(this).closest('tr');
      $(this).closest("tr").remove(); // remove row
      $('#example').append($row);
        });

Use Javascript to get table content in the form on mouse click

There are times when you need to get all table contents in the form to edit. This could be done by calling a function on row click or any button click. Below is the code which explains how you could do that.

$(document).ready(function(){
      $('#htmlgrid tbody tr td').on('click', 'a', function(event){

            var first_cell = $('td:eq(0)', $(this).parent().parent()).text();
            var second_cell = $('td:eq(1)', $(this).parent().parent()).text();
            var third_cell = $('td:eq(2)', $(this).parent().parent()).text();

            var answer = prompt('Please enter your Password', '');
            if (answer!=null){
                  answer=$.trim(answer);
                  answer=answer.toUpperCase();
                  password = $.trim(answer);
                  password_from_db = password_from_db()
                  if(password==password_from_db){
                        document.forms[0].elements['first_cell'].value = first_cell;
                        document.forms[0].elements['second_cell'].value = second_cell;
                        document.forms[0].elements['third_cell'].value = third_cell;
                  }
            }
                  else{
                        alert('wrong_password');	
                  }
      });
});

Hiding table row using jQuery

There are many ways to hide table rows. You can either use jQuery or CSS.
This is jQuery code which will hide first and second th and td of the table.

<$(document).ready(function() {
      $('td:nth-child(0),th:nth-child(0)').hide();
      $('td:nth-child(1),th:nth-child(1)').hide();
});

 

To hide table row using CSS you can use "display: none"

Single checkbox functionality for table rows.

$('table tr').click(function() {

 checkBox = $(this).children('td').children('input[type=checkbox]');

 if(checkBox.attr('checked'))
  checkBox.attr('checked', '');
 else
  checkBox.attr('checked', 'checked');
});

Functionality to check/uncheck all checkbox in our table by clicking only one checkbox

$('.check-all').click(function() {

 checkBox = $('table tr').children('td').children('input[type=checkbox]');

 if($(this).attr('checked'))
  checkBox.attr('checked', 'checked');
 else
  checkBox.attr('checked', ''); 
});

simple Drag and Drop using jQuery

CSS code for drag and drop in HTML table

ul li {
    min-width: 200px;
}
.dragging li.ui-state-hover {
    min-width: 240px;
}
.dragging .ui-state-hover a {
    color:green !important;
    font-weight: bold;
}
th,td {
    text-align: right;
    padding: 2px 4px;
    border: 1px solid;
}
.connectedSortable tr, .ui-sortable-helper {
    cursor: move;
}
.connectedSortable tr:first-child {
    cursor: default;
}
.ui-sortable-placeholder {
    background: yellow;
}

jQuery code for Drag and Drop HTML table

$(document).ready(function() {
    $tabs = $(".tabbable");

    $('.nav-tabs a').click(function(e) {
        e.preventDefault();
        $(this).tab('show');
    })

    $( "tbody.connectedSortable" )
        .sortable({
            connectWith: ".connectedSortable",
            items: "> tr:not(:first)",
            appendTo: $tabs,
            helper:"clone",
            zIndex: 999990,
            start: function(){ $tabs.addClass("dragging") },
            stop: function(){ $tabs.removeClass("dragging") }
        })
        .disableSelection()
    ;

    var $tab_items = $( ".nav-tabs > li", $tabs ).droppable({
      accept: ".connectedSortable tr",
      hoverClass: "ui-state-hover",
      over: function( event, ui ) {
        var $item = $( this );
        $item.find("a").tab("show");

      },
      drop: function( event, ui ) {
        return false;
      }
    });

});

Demo: http://jsfiddle.net/Kzf62/514/

3 thoughts on “Create Editable HTML table using jQuery & JavaScript”

  1. Shabina Siddique

    The first example code is to create editable cell in tale. Try using that, let me know if you have difficulties implementing the code

  2. I’m not understanding the “cellEditing” what is that where to add that class in HTML

Comments are closed.

Scroll to Top