Published on: 17 Dec, 2013

How to add and delete a table row in javascript?

Tumblr Digg Google Plus

In this quick tutorial, you will learn how to add and delete rows dynamically in Javascript. You can see the real example below. Further reading, you will find quick explanation on how to do it. The codes provided come with comment/explanations.

See how the table row can be added and deleted automatically by using javascript.

Checkbox Sample value

Firstly you will need to create the following javascript function:

function addSampleRow(id) {
    /*** We get the table object based on given id ***/
    var objTable = document.getElementById(id);

    /*** We insert the row by specifying the current rows length ***/
    var objRow = objTable.insertRow(objTable.rows.length);

    /*** We insert the first row cell ***/
    var objCell1 = objRow.insertCell(0);

    /*** We  insert a checkbox object ***/
    var objInputCheckBox = document.createElement("input");
    objInputCheckBox.type = "checkbox";

     /*** We  insert the second row cell ***/
    var objCell2 = objRow.insertCell(1);
    var currentDate = new Date()

    /*** We  add some text inside the celll ***/
    objCell2.innerHTML = "You add me on " + currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds();

function removeSampleRow(id) {
    /***We get the table object based on given id ***/
    var objTable = document.getElementById(id);

    /*** Get the current row length ***/
    var iRow = objTable.rows.length;

	/*** Initial row counter ***/
	var counter = 0;

    /*** Performing a loop inside the table ***/
	if (objTable.rows.length > 1) {
		for (var i = 0; i < objTable.rows.length; i++) {

			 /*** Get checkbox object ***/
			var chk = objTable.rows[i].cells[0].childNodes[0];
			if (chk.checked) {
				/*** if checked we del ***/
				counter = counter + 1;

		/*** Alert user if there is now row is selected to be deleted ***/
		if (counter == 0) {
			alert("Please select the row that you want to delete.");
		/*** Alert user if there are no rows being added ***/
		alert("There are no rows being added");

Next is to create the html code as below:

	<input type="button" id="btnAdd" value="Add Sample Row" onclick="addSampleRow('tblSample')"> 
	<input type="button" id="btnDelete" value="Delete Selected Rows" onclick="removeSampleRow('tblSample')">

<table id="tblSample" border="1" cellspacing="2" cellpadding="10">
        <td>Sample value</td>

That's all you need to do, you can see the action on how the scripts work above. Click here to see the action


There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.