I have a jsfiddle here of the script I'm using to dynamically add rows to a field but have a problem.
On my form I have the 1st row that I want to duplicate with the script. The row consists of 6 inputs named job_date1
, tech_name1
, cost_code1
, pay_rate1
, total_hours1
, and sub_total1
.
When the second row is created via the script I now need the new rows input names to be set by the script if possible to job_date2
, tech_name2
, cost_code2
and so on and with each new row created I need the end digit to move up one.
Here is the code:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
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;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null !== chkbox && true === chkbox.checked) {
if(rowCount <= 1) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
catch(e) {
alert(e);
}
}
Here's a simple solution:
newcell.children[0].name = newcell.children[0].name + rowCount;
As you count each newly added row, add that variable to each of the input elements.
Here's the jsFiddle (be sure to check your console when you run the function to see the console log).
For the first log, it returns:
chk1
txt1
tech_name1
cost_code1
txt1
For the second element that's created
chk2
txt2
tech_name2
cost_code2
txt2
etc.
I have a simpler suggestion. Instead of having job_date1
, job_date2
, etc., name your fields job_date[]
(all of the job date fields).
Eg PHP automatically recognizes this and $_POST["job_date"]
would be an array with all the values for job date in the order they appear on the html page.
So instead of $_POST["job_date" . $i]
$_POST["job_date" . $i]
you would use $_POST["job_date"][$i]
.
I don't know what technology you use for the backend, but I'm sure you can achieve the same effect.
It will be more robust and elegant and you don't have to care about re-numbering when you add nor remove rows.
Edit: More details about this technique in PHP can be found in PHP FAQ and Example #3 here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.