SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Guru
    Join Date
    Nov 2004
    Location
    England
    Posts
    698
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    Question Adding Rows to Table

    Hi guys,

    I have this fairly horrible table that I need to add rows to onclick. I can get it to do it easily enough by setting the tbody id to "tbodyid" and using this simple JS:

    Code Javascript:
    var rowcount = 0;
    function addrow(){
        rowcount++;
        document.getElementById("tbodyid").innerHTML += '<tr>...</tr>';
    }

    Works beautifully, but the problem that I've got is that if I put any text in any inputs in the new rows, when I add an extra field they all blank themselves again, which is a bit annoying. Is there a simple solution?

    (BTW, the rowcount var is for incrementing field IDs)

  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,197
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    You may need to change it a little but it does exactly what your doing already just using the DOM to build the elements

    Code JavaScript:
    function addrow(){
        var trElement = document.createElement('tr');
        var tdElement = document.createElement('td');
     
        // Set the element attributes
        var inElement = document.createElement('input');
        inElement.setAttribute('type', 'text');
        inElement.setAttribute('size', '25');
     
        // Append the new elements together
        tdElement.appendChild(inElement);
        trElement.appendChild(tdElement)
     
        document.getElementById('tbodyid').appendChild(trElement);
    }

  3. #3
    SitePoint Guru
    Join Date
    Nov 2004
    Location
    England
    Posts
    698
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Thanks for that. I may have simplified my original request a bit so I ended up with some large JS to build the whole thing (I actually need to add 5 rows with TH, TD, LABEL, INPUT, TEXTAREA and some text nodes) BUT it does work now, so thanks a lot

  4. #4
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,197
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Your welcome


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
  •