Saturday, July 5, 2008

PHP POST Variable Not Detecting Dynamically Created Form Elements Through Javascript

Right now I'm working on a project where I need to generate an unlimited number of form elements. Let's say it's a T-shirt store. And we need to be able to add any number of sizes for each t-shirt design. We could do that a number of ways, but a simple way would be to add a Javascript link:
<a href="#" onclick="addSize('sizes');return false;">Add Size</a>
You would probably set up the elements in a table, like so:
<table id="sizes">
<tr>
<th>Size</th>
<th>Quantity</th>
</tr>
<tr>
<td><input name="txtSize[]" type="text"></td>
<td><input name="txtQuantity[]" type="text"></td>
</tr>
</table>
I like using the [] to make the form elements an array. I believe most browsers will automatically make a form element an array if it has the same name, but I like to be doubly sure. Then you could use the HTML DOM functions insertRow and insertCell.
function addSize(tableId) {
tableObj = document.getElementById(tableId);
numRows = tableObj.rows.length;
lastRow = tableObj.rows[numRows - 1];
numCells = lastRow.cells.length;
newRow = tableObj.insertRow(numRows);
for(var i = 0; i < numCells; i++) {
oldCellHTML = lastRow.cells[i].innerHTML;
newRow.insertCell(i);
newCell = newRow.cells[i];
newCell.innerHTML = oldCellHTML;
}
}
All seems to work fine, you see the new fields populate. But once you post the form, you may run into the problem I did. There was only one element in each fields array.

I started looking into it, and couldn't figure it out. So I started writing this simple example, and it worked fine. But my actual project still didn't work. So I was on the hunt again to figure out why.

I found this post, which helped me find the issue with my original project. Turns out it all had to do with how you nest your form tag. My mistake was that I was putting my form tag between the table and tr tag, instead of nesting the entire table inside the form.

No comments: