Jquery add and remove table row

Hi all,

Just wanted your help. The code you have given on the beginning for adding and removing rows really helped me a lot. but still i need some help since i am new to jquery.
I have a UI and on which i have to click on link and that should bring up a dialog box and that dialog box should contain all those add and remove functionality and then i have to submit the form. Submitting the form is ok but i am unable to click the link and load the contents to the dialog box.

could you help me out on this ?

Thanks
smruti

Hi smruti,

Probably.
The first thing we would need to see is some code.
Could you provide a link to a page where I can see the problem you are having?

Pullo,
Thanks for your reply. Finally today I solved my issue. I am looking into the other phase of the code. Will ask for your help if I face any issue.

Hi All,

Below is my code to add and remove rows.

<html>
<head>
<script src=“http://code.jquery.com/jquery-1.5.1.min.js”></script>
<script>
$(document).ready(function() {
var id = 0;

		$("table.dynamictbl button.add").click(function() {
			id++;
			var temp = $(this).parents("table.dynamictbl");
			
			// Get a new row based on the prototype row
			var prot = temp.find(".prototype").clone();
			prot.attr("class", "");
			prot.find(".id").attr("value", id);
			
			temp.find("tbody").append(prot);
		});

		$("table.dynamictbl button.remove").live("click", function() {
			$(this).parents("tr").remove();
			
		});
	});
	&lt;/script&gt;

&lt;/head&gt;
&lt;body&gt;
	&lt;table class="dynamictbl" border="1"&gt;
		&lt;thead&gt;
			&lt;tr&gt;
				&lt;th&gt;KEY&lt;/th&gt;
				&lt;th&gt;VALUE&lt;/th&gt;
				&lt;th&gt;&lt;button class="add"&gt;Add&lt;/button&gt;&lt;/th&gt;
			&lt;/tr&gt;
			
		&lt;/thead&gt;
		&lt;tbody&gt;
			&lt;tr class="prototype"&gt;
				&lt;td&gt;&lt;input type="text" name="key[]" value="" /&gt;&lt;/td&gt;
				&lt;td&gt;&lt;input type="text" name="value[]" value="" /&gt;&lt;/td&gt;
				&lt;td&gt;&lt;button class="remove"&gt;Remove&lt;/button&gt;&lt;/td&gt;
			&lt;/tr&gt;
			
		&lt;/tbody&gt;
		
	&lt;/table&gt;
&lt;/body&gt;

</html>

my question is now i want to save the data entered in the table. And since this is a dynamic table i need to go through each row in order to save the data of each row.
Can you tell me how to read each row to save the data entered ?

thanks

Hi,

First question would be: how do you want to save the data (e.g. cookie, local storage, to file)?

Hi,
I want to send those value to server side. so it will be a post data.

Also i am seeing that after entering any value on the key and value column (code given above), if i click on the add button, its creating a new row but also its coping the contents of the previous row. it should copy the row only not the contents. Can you send me some suggestions on that ?

What I would do then, is have a button (“Save” or something), that when you click on it, grabs all of the data out of the table and stores it in an JSON object.
Once you have done this, you can pass the JSON object via AJAX to your server-side script.

I fixed this for you.
I also updated the script to run with the latest 1.x jQuery.

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Add/remove table row</title>
  </head>
  
  <body>
    <table class="dynamictbl" border="1">
      <thead>
        <tr>
          <th>KEY</th>
          <th>VALUE</th>
          <th><button class="add">Add</button></th>
        </tr>
      </thead>
      <tbody>
        <tr class="prototype">
          <td class="row1"><input type="text" name="key[]" value="" /></td>
          <td class="row2"><input type="text" name="value[]" value="" /></td>
          <td><button class="remove">Remove</button></td>
        </tr>
      </tbody>
    </table>
    <button id="save">Save contents</button>
    
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script>
      var id = 0;
      $("table.dynamictbl button.add").click(function() {
        id++;
        var temp = $(this).parents("table.dynamictbl");
        // Get a new row based on the prototype row
        var prot = temp.find(".prototype").clone();
        $(prot[0]).find("input").val("");
        prot.attr("class", "");
        prot.find(".id").attr("value", id);
        temp.find("tbody").append(prot);
      });
      
      $(document.body).on("click", "table.dynamictbl button.remove", function() {
        $(this).parents("tr").remove();
      });
      
      $("#save").click(function(){
        var $rows = $("table.dynamictbl > tbody > tr");
        var data = {};
        
        $rows.each(function(index){
          var r1 = $(this).find(".row1 > input[type=text]").val();
          var r2 = $(this).find(".row2 > input[type=text]").val();
          data[index]= {"key" : r1, "value" : r2};
        });
        
        // Do your AJAX Magic here
        console.log(JSON.stringify(data));
      })
    </script>
  </body>
</html>

Hope that helps.

wow…You made my day. This code is working perfectly fine. Thanks again

No probs :slight_smile:
Thanks for taking the time to report back.

Hi,
i want another help. After added rows and value in the table and when i am clicking the “Save contents” button, i am getting value like this

{“0”:{“keyname”:“asdas”,“keyvalue”:“asasdas”},“1”:{“keyname”:“asdsaasdasd”,“keyvalue”:“sadsadsad”},“2”:{“keyname”:“asdsadasdasd”,“keyvalue”:“sadasdsad”}}

my question: is there any way to ignore these values “0”: “1”: and “2”:
because when i am sending it to server side as a list, these values ( “0”: “1”: and “2”: ) are getting added to the list and causing failure in the post method.

thanks

Sure,

Just do something like:

var data = [];

$rows.each(function(index){
  var r1 = $(this).find(".row1 > input[type=text]").val();
  var r2 = $(this).find(".row2 > input[type=text]").val();
  data.push({"key" : r1, "value" : r2});
});

Or better:

data.push([r1, r2]);

Thanks pullo…
Now the problem is when i am adding data.push instead of data[index]. its populating only the values present on the first row. it is not adding the successive rows value into the list.

Oh dear!

Here’s a basic example with everything working.
Compare what you have with this and try and work out what’s going wrong.

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Add/remove table row</title>
  </head>

  <body>
    <table class="dynamictbl" border="1">
      <thead>
        <tr>
          <th>KEY</th>
          <th>VALUE</th>
          <th><button class="add">Add</button></th>
        </tr>
      </thead>
      <tbody>
        <tr class="prototype">
          <td class="row1"><input type="text" name="key[]" value="" /></td>
          <td class="row2"><input type="text" name="value[]" value="" /></td>
          <td><button class="remove">Remove</button></td>
        </tr>
      </tbody>
    </table>
    <button id="save">Save contents</button>

    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script>
      var id = 0;
      $("table.dynamictbl button.add").click(function() {
        id++;
        var temp = $(this).parents("table.dynamictbl");
        // Get a new row based on the prototype row
        var prot = temp.find(".prototype").clone();
        $(prot[0]).find("input").val("");
        prot.attr("class", "");
        prot.find(".id").attr("value", id);
        temp.find("tbody").append(prot);
      });

      $(document.body).on("click", "table.dynamictbl button.remove", function() {
        $(this).parents("tr").remove();
      });

      $("#save").click(function(){
        var $rows = $("table.dynamictbl > tbody > tr");
        var data = [];

        $rows.each(function(index){
          var r1 = $(this).find(".row1 > input[type=text]").val();
          var r2 = $(this).find(".row2 > input[type=text]").val();
          data.push([r1, r2]);
        });

        // Do your AJAX Magic here
        console.log(JSON.stringify(data));
      })
    </script>
  </body>
</html>

FWIW, I would do it using an array of arrays.
On the server side you can then iterate over these and manipulate the data as necessary.

yes this changes are working.
but can we get separate names and value for each row. so that it will be easy to update those data in database and get those data again to table to modify.

Can we use names like this

key0 value0
key1 value1
key2 value2

Sorry, I’m not with you.
Could you post an example of what you would like the data structure to look like?

For example i want the data structure to be like this

{“keyvaluepair”:[{“keyname0”:“url”,“keyvaue0”:“sampleurl”},{“keyname1”:“sleeptime”,“keyvaue1”:“3”}, {“keyname2”:“browser”,“keyvaue2”:“firefox”}…]

That would be this:

var $rows = $("table.dynamictbl > tbody > tr");
var data = {"keyvaluepair": []};

$rows.each(function(index){
  var r1 = $(this).find(".row1 > input[type=text]").val();
  var r2 = $(this).find(".row2 > input[type=text]").val();
  var obj = {};
  obj["keyname" + index] = r1;
  obj["keyvalue" + index] = r2;
					
  data["keyvaluepair"].push(obj);
});

HTH

Thanks a ton pullo. It worked. Finally its matching with other data sequence.

Thanks again :slight_smile:

Hi Pullo,

By using above code i am able to insert all those values into database successfully.
On my UI, i have two parts

  1. Add personal details of a person along with the data present in the dynamic table.
  2. search of a person and modify data along with the values present in the table.

i am able to insert data into database.
Also i am able to get a string of data inserted in database back to UI but unable to populate those values into the table rows.

sending data into database in the below format:
{“keyvaluedata”:[{“keyname0”:“url”,“keyvaue0”:“sampleurl”},{“keyname1”:“sleeptime”,“keyvaue1”:“3”}, {“keyname2”:“browser”,“keyvaue2”:“firefox”}, {“keyname3”:“surname”,“keyvaue3”:“sa”}…]

getting a string of inserted data from database for the dynamic table in the format:
keyvaluedata :{“url”:“sampleurl”,“sleeptime”:“3”,“browser”:“firefox”,“surname”:“sa”,…}

Now the difficulty is to populate again these keyname and keyvalues into the dynamic table.
Can you give some suggestions ?

Thanks