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:

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)

You may need to change it a little but it does exactly what your doing already just using the DOM to build the elements

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);
}

Your welcome :slight_smile:

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