SitePoint Sponsor

User Tag List

Results 1 to 25 of 25
  1. #1
    SitePoint Member
    Join Date
    Jun 2013
    Posts
    14
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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
    Last edited by ScallioXTX; Jun 3, 2013 at 12:45. Reason: made greeting generic

  2. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,873
    Mentioned
    208 Post(s)
    Tagged
    12 Thread(s)
    Hi smruti,

    Quote Originally Posted by smruti View Post
    could you help me out on this ?
    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?

  3. #3
    SitePoint Member
    Join Date
    Jun 2013
    Posts
    14
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.

  4. #4
    SitePoint Member
    Join Date
    Jun 2013
    Posts
    14
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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();

    });
    });
    </script>

    </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><input type="text" name="key[]" value="" /></td>
    <td><input type="text" name="value[]" value="" /></td>
    <td><button class="remove">Remove</button></td>
    </tr>

    </tbody>

    </table>
    </body>
    </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

  5. #5
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,873
    Mentioned
    208 Post(s)
    Tagged
    12 Thread(s)
    Hi,

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

  6. #6
    SitePoint Member
    Join Date
    Jun 2013
    Posts
    14
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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 ?

  7. #7
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,873
    Mentioned
    208 Post(s)
    Tagged
    12 Thread(s)
    Quote Originally Posted by smruti View Post
    I want to send those value to server side. so it will be a post data.
    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.

    Quote Originally Posted by smruti View Post
    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 ?
    I fixed this for you.
    I also updated the script to run with the latest 1.x jQuery.

    Code:
    <!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.

  8. #8
    SitePoint Member
    Join Date
    Jun 2013
    Posts
    14
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    wow..You made my day. This code is working perfectly fine. Thanks again

  9. #9
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,873
    Mentioned
    208 Post(s)
    Tagged
    12 Thread(s)
    No probs
    Thanks for taking the time to report back.

  10. #10
    SitePoint Member
    Join Date
    Jun 2013
    Posts
    14
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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

  11. #11
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,873
    Mentioned
    208 Post(s)
    Tagged
    12 Thread(s)
    Sure,

    Just do something like:

    Code JavaScript:
    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:

    Code JavaScript:
    data.push([r1, r2]);

  12. #12
    SitePoint Member
    Join Date
    Jun 2013
    Posts
    14
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.

  13. #13
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,873
    Mentioned
    208 Post(s)
    Tagged
    12 Thread(s)
    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.

    Code:
    <!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>

  14. #14
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,873
    Mentioned
    208 Post(s)
    Tagged
    12 Thread(s)
    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.

  15. #15
    SitePoint Member
    Join Date
    Jun 2013
    Posts
    14
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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
    ...............
    ...............

  16. #16
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,873
    Mentioned
    208 Post(s)
    Tagged
    12 Thread(s)
    Sorry, I'm not with you.
    Could you post an example of what you would like the data structure to look like?

  17. #17
    SitePoint Member
    Join Date
    Jun 2013
    Posts
    14
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    For example i want the data structure to be like this

    {"keyvaluepair":[{"keyname0":"url","keyvaue0":"sampleurl"},{"keyname1":"sleeptime","keyvaue1":"3"}, {"keyname2":"browser","keyvaue2":"firefox"}.......]

  18. #18
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,873
    Mentioned
    208 Post(s)
    Tagged
    12 Thread(s)
    That would be this:

    Code JavaScript:
    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

  19. #19
    SitePoint Member
    Join Date
    Jun 2013
    Posts
    14
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks a ton pullo. It worked. Finally its matching with other data sequence.

    Thanks again

  20. #20
    SitePoint Member
    Join Date
    Jun 2013
    Posts
    14
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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

  21. #21
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,873
    Mentioned
    208 Post(s)
    Tagged
    12 Thread(s)
    Quote Originally Posted by smruti View Post
    Now the difficulty is to populate again these keyname and keyvalues into the dynamic table.
    Can you give some suggestions ?
    Sure. I rewrote the script a little to do what you ask:

    Code:
    <!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>
        <button id="insert">Insert some content</button>
        
        <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
        <script>
          var $row = $("tr.prototype").clone().removeClass("prototype");;
          
          $("table.dynamictbl button.add").on("click", function() {
            $("table").append($row.clone());
          });
          
          $(document.body).on("click", "table.dynamictbl button.remove", function() {
            $(this).parents("tr").remove();
          });
          
          $("#insert").on("click", function(){
            var data = {keyvaluedata :{"url":"sampleurl","sleeptime":"3","browser":"firefox","surname":"smith"}}
            $.each(data["keyvaluedata"], function(k, v){
              var r = $row.clone();
              r.find("td.row1 > input").val(k);
              r.find("td.row2 > input").val(v);
              $("table").append(r);
            })
          });
          
          $("#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>

  22. #22
    SitePoint Member
    Join Date
    Jun 2013
    Posts
    14
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Pullo,

    I am trying to implement this into my code and will let you know once implemented. Hope will get back to you with good news. Thanks again.

  23. #23
    SitePoint Member
    Join Date
    Jun 2013
    Posts
    14
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi pullo,

    I am facing some issue with the onsert button (which will populate the values to table). when i am clicking the insert button its simply submitting the page, not populating any value into table.

    concerns:
    also please let me know if it is possible to call the function from another function without using "insert" button. Like in the below code i am calling "populatedatafrmdb" function. I am getting proper keyvaluedata inside the "populatedatafrmdb" function like below

    {"url":"sampleurl","sleeptime":"3","browser":"firefox","surname":"smith"}

    please see the attached code.

    Note: since my code size was big, i have removed some part which is not required for this issue.

    thanks

  24. #24
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,873
    Mentioned
    208 Post(s)
    Tagged
    12 Thread(s)
    Hi,

    Quote Originally Posted by smruti View Post
    when i am clicking the insert button its simply submitting the page, not populating any value into table.
    It sounds to me like you have included the button within a form.
    In this case you need to prevent the button's default action.

    Code JavaScript:
    $("button").on("click", function(e){
      e.preventDefault();
      ...
    })

    http://api.jquery.com/event.preventDefault/

    Quote Originally Posted by smruti View Post
    also please let me know if it is possible to call the function from another function without using "insert" button.
    Yes, it is. The button was just to demonstrate the functionality.

    Quote Originally Posted by smruti View Post
    please see the attached code.
    The attached code is almost two thousand lines long.
    It would help if you could strip this down to a minimum, so that you demonstrate the problem you are having, but nothing more.

  25. #25
    SitePoint Member
    Join Date
    Jun 2013
    Posts
    14
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi pullo,

    Thanks for your suggestions. I have modified the code to not to use button and it worked fine. Thanks for your help


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •