Wednesday, January 5, 2011

Add/ Remove rows using javascript or Jquery

Jquery is one of the great and coolest feature in the web. you can desing your application any thing as u want with asynchronous call.
here i have created one small application for adding or removing the rows from your tables.

many times we are not sure how much length of user input is for ex. in case of
address field we are not sure how much length of data is so that time this coolest add/remove rows function will use.
just try it .

here is the basic java script.


<html>
<head>
<title> Add/Remove Rows in Table </title>
<script language="javascript">
function addRow(tableID) {

var table = document.getElementById(tableID);

var rowCount = table.rows.length;
var row = table.insertRow(rowCount);

var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
cell1.appendChild(element1);

var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount + 1;

var cell3 = row.insertCell(2);
var element2 = document.createElement("input");
element2.type = "text";
cell3.appendChild(element2);
}

function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;

for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}

}
}catch(e) {
alert(e);
}
}
function SubmitForm()
{
// your form Validation code goes here ...
}

</SCRIPT>
</head>
<body>
<TABLE id="dataTable" width="350px" border="1">
<TR>
<TH>Select</TH>
<TH>Sr. No.</TH>
<TH>Value</TH>
</TR>
<TR>
<TD><INPUT type="checkbox" name="chk"/></TD>
<TD> 1 </TD>
<TD> <INPUT type="text" /> </TD>
</TR>
</TABLE>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<INPUT type="button" value="submit" onclick="SubmitForm()" />
</BODY>
</HTML>



hope u like it .,.... just commnet it.. the jquery example i will post it on my next post.

5 comments:

  1. Firstly i like to appreciate your efforts taken to share such a great source with all. Really a great post which is simple to read and easy to understand. Great Job buddy... keep this going on.

    ReplyDelete
  2. I really enjoyed your blog post, i always got good, relevant and useful information from your new and unique posts, i m sure your blog will keep us continues update. Thanks for providing us such useful information.
    wholesale nursery

    ReplyDelete
  3. Its really nice. Its help me lot !!

    ReplyDelete
  4. if add extra text boxes it does not give any output

    ReplyDelete
  5. Hi Rajini,

    it is, you only need to call create one function and pass the tr(row id)
    and base on that you can just add the for loop and to remove or add the other rows. if you want more help just send me PM i will send you the sample code

    ReplyDelete