I am trying to make a page where users can add as many rows to a table as they want, and then the values of the inputs (there is an input in each cell of the table) are passed back to the page.
My problem comes when trying to make the name of each dynamically generated input box different. I've tried to create a variable to do it, but the syntax I'm using, which works in other places, doesn't seem to work when creating new elements.
Here is the code in question:
if ($_POST['dept_1'] != null){ //If there was an input
$i = intval($_POST['num_of_rows']);
while ($i != 0){
$dept = $_POST['dept_' . $i];
$hours = $_POST['hours_' . $i];
echo $dept . " " . $hours . "\n";
$i--;
}
}
.....
var i = 2;
$("document").ready(function(){
$("#newrow").click(function(e){
$("#maintable").append('<tr> \
<td><input type="text" name="dept_" + i size="5" maxlength="5" /></td> \
<td><input type="text" name="hours_" + i size="5" maxlength="1" /></td> \
</tr>');
alert("dept_" + i);
e.preventDefault();
$("#hiddenvalue").attr("value", "" + i + "");
i = i + 1;
});
});
$POST['dept' . $i] works when $i = 1, because dept_1 is written into the HTML of the page.
alert("dept_" + i) works, concatenating the value of i to the string.
name="dept_" + i does not work. Inspecting the new element, its name is "dept_ + i"
Why is this happening, and how can I fix it?