jQuery to add/ remove html table rows dynamically and getting values in servlet.

In this tutorial, let us see how to add/ remove rows dynamically in a HTML table using jQuery. Yo can go through my earlier tutorial to do the same task using Javascript. jQuery simplifies the task of adding/ removing html table rows dynamically. Now let us see an example for Ticket Booking. In this example, we will add/ remove passenger details dynamically before submitting the data to the server. Also will see that how to retrieve the values of the dynamically generated rows at server side using servlet

Let us assume that each row has the following 5 fields.
S.No
Name (using Text Box)
Age (using Text Box)
Gender (using Combo Box)
Action (remove)(Using Button)

and the html code for each row will be as given below.

                      trow=  "<tr><td class='sNo'>"+sno+"</td>"+
                           "<td><input name='pName' type='text'></td>"+
               		   "<td><input name='age' type='text'></td>"+
               		   "<td><select name='gender'><option value='M'>Male</option><option value='F'>Female</option></select></td>"+
               		  "<td><button type='button' class='rButton'>Remove</button></td></tr>"; 

where sno will be

sno=$(‘#pTable tr’).length;  

+1 not required, because one row is already there in the table which is the heading of the table.

where pTable is the table id.

To add above row in the table dynamically using jQuery, use the below statement.

$(‘#pTable’).append(trow);

Each row will have remove button.

To remove the current row by clicking on the remove button using jQuery, you can use the below statements

$(document).on('click', 'button.rButton', function () {
       $(this).closest('tr').remove();
       arrangeSno();
     return false;
 });

OR


$(".rButton").live('click', function(){
	$(this).closest('tr').remove();
	 arrangeSno();
	 return false;
}); 

arrangeSno() function will arrange serial nos, when we remove table row.

function arrangeSno()

	{
           var i=0;
            $('#pTable tr').each(function() {
                $(this).find(".sNo").html(i);
                i++;
             });

	} 

The above statements traverse each rows in the table and change the serial number value.

The complete code for adding/ removing rows dynamically in the html table and arranging serial number is given below.

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>jQuery add/remove rows in html table</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

</head>
<body>

<script>

function arrangeSno()

	{
           var i=0;
            $('#pTable tr').each(function() {
                $(this).find(".sNo").html(i);
                i++;
             });

	}

$(document).ready(function(){
$('#addButId').click(function(){
	               var sno=$('#pTable tr').length;
                       trow=  "<tr><td class='sNo'>"+sno+"</td>"+
                           "<td><input name='pName' type='text'></td>"+
                  		   "<td><input name='age' type='text'></td>"+
                  		   "<td><select name='gender'><option value='M'>Male</option><option value='F'>Female</option></select></td>"+
                  		  "<td><button type='button' class='rButton'>Remove</button></td></tr>";
	                  $('#pTable').append(trow);
                    });
                     });

$(document).on('click', 'button.rButton', function () {
       $(this).closest('tr').remove();
       arrangeSno();
     return false;
 });

/*$(".rButton").live('click', function(){
	$(this).closest('tr').remove();
	arrangeSno();
     return false;
});*/

 </script>

<h1>jQuery Add Remove Rows Dynamically in a Html Table Example</h1>

<form method="post" action="Process">

    <p>Enter Passenger Details. Press Add Passengers button to add more passengers.</p>

    <table id="pTable">
        <tbody>
        <tr>
            <td>S.No</td>
            <td>Name</td>
            <td>Age</td>
            <td>Gender</td>
            <td>Action</td>
        </tr>

    </tbody></table>
    <br/>
        <input id="addButId" type="button" value="Add Passengers">

    <br><input type="submit" value="Submit">
</form>

</body>
</html>

For getting the values of dynamically generated rows at server side using servlet, use the following code


package javaonline;

.....
......

/**
 * Servlet implementation class Process
 */
@WebServlet("/Process")
public class Process extends HttpServlet {
	...
	...
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		String name[]=request.getParameterValues("pName");
		String age[]=request.getParameterValues("age");
		String gender[]=request.getParameterValues("gender");

		System.out.println(name.length);

		for (int i=0;i<name.length;i++)
			System.out.println(name[i]  + " " + age[i] + " " + gender[i]);

	}

}

Running  the above code, by calling

http://localhost:8080/TestWeb/jQueryAddRemoveRows.html

add remove rows dynamically

 

Added 3 Rows

add remove rows dynamically1

Removed one row

add remove rows dynamically2

Submitted above rows and the values in server side.

add remove rows dynamically3

 

Try Live Demo

 

You may also like

Leave a Reply

Be the First to Comment!