Tutorials - HTML Table Add Row submit to PHP

Dynamically add rows to an HTML table, then submit to PHP

Try It

tblInsertRowPHP header

Source

JavaScript source

// mredkj.com
// 2006-07-21
function insertRowPHP()
{
  var tbl = document.getElementById('tblInsertRowPHP');
  var iteration = tbl.tBodies[0].rows.length;
  newRow = tbl.tBodies[0].insertRow(-1);
  var newCell = newRow.insertCell(0);
  newCell.innerHTML = 'row ' + iteration;
  var newCell1 = newRow.insertCell(1);
  var el = document.createElement('input');
  el.type = 'text';
  el.name = 'txtRow[]';
  el.id = 'txtRow' + iteration;
  el.size = 40;
  newCell1.appendChild(el);
}
function deleteAllRows(tblId)
{
  var tbl = document.getElementById(tblId);
  for (var i=tbl.tBodies[0].rows.length-1; i>=0; i--) {
    tbl.tBodies[0].deleteRow(i);
  }
}

Explanation

A few people have asked me how to submit dynamically added rows server side to PHP, so I wrote a simplified version of my Table Add Row script, and a simple PHP page at my other site innovationlost.org. When you click the Submit button above it will submit the row textbox values to that PHP page.

The thing is you don't really need to do anything special to submit the values server side. As long as you give your form elements a name, they will be submitted. The trick is trying to do something with the values in PHP.

One of the easiest ways to reference the row data when submitting to PHP is to name each group of form elements with brackets []. In the JavaScript above, refer to this line:

el.name = 'txtRow[]';

Then on the PHP side, you can just iterate the values as an array.

About this page: