David D.
David D.

Reputation: 367

Output Dynamic Table Data

I am creating an invoice website for my intranet.

I have the following code for making a dynamic table row inside the html that generates rows up to how much we need for the invoice.

 function addRow(tableID) {

        var table = document.getElementById(tableID);

        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);

        var colCount = table.rows[1].cells.length;

        for(var i=0; i<colCount; i++) {

            var newcell = row.insertCell(i);

            newcell.innerHTML = table.rows[1].cells[i].innerHTML;
            //alert(newcell.childNodes);
            switch(newcell.childNodes[0].type) {
                case "text":
                        newcell.childNodes[0].value = "";
                        break;
                case "checkbox":
                        newcell.childNodes[0].checked = false;
                        break;
                case "select-one":
                        newcell.childNodes[0].selectedIndex = 0;
                        break;
            }
        }
    }

After inserting data through the form, I want to output the table data through php echo. But I can't figure out how to output every row from the dynamic table because right now it just gives me the last row.

In the following fashion I want to output the data:

echo $var_name."<br>";

Right now I have 5 variables for each row in the table, but they only give me the latest row input (logical)

Upvotes: 0

Views: 968

Answers (1)

Barmar
Barmar

Reputation: 781058

You need to give the form fields names ending in []. When the form is submitted, PHP will combine all the fields with the name name[] into an array in $_POST['name']. You can then iterate through these arrays to get all the rows of the form.

The form should look something like:

<form method="post" action="your URL">
  <table>
    <tr><td><input type="text" name="somename[]"></td>
        <td><select name="somemenu[]">
              <option value="">Please choose</option>
              <option value="1">Option 1</option>
              <option value="2">Option 2</option>
              ...
            </select></td>
    </tr>
  </table>
</form>

Then your PHP can do:

foreach (array_keys($_POST['somename']) as $key) {
  // Do something with $_POST['somename'][$key] and $_POST['somemenu'][$key]
}

Upvotes: 1

Related Questions