I'm having a little trouble with some JS that adds rows to a table/form on my page. The button to delete the added row is also added dynamically. The row indexes start out okay but they somehow get messed up later on. If I click the remove button for row 1, it removes row 1. If I remove row 2, it removes row 2. If I remove row 5, it removes the last row (whatever index it is). I assume the button isn't passing a valid index to the function but I have no way to examine it, so...???
Here's the relevant code:
function addEquip()
{
var tbl = document.getElementById('equip');
var lastRow = tbl.rows.length;
// Add row...
var row = tbl.insertRow(-1);
var rownum = row.rowIndex;
// ...stuff to add cells/form elements here, etc...
// Remove button...
var rmv = document.createElement('input');
rmv.type = 'button';
rmv.name = 'remove' + rowind;
rmv.value = 'remove';
rmv.onclick = function () { delEquip(rownum) };
cellB.appendChild(rmv);
}
function delEquipment(rownum)
{
var tbl = document.getElementById('equip');
// Delete the current row...
tbl.deleteRow(rownum);
}
I'm thinking that maybe the fact that the table starts with an unknown number of rows could be the problem. Anyway, here's how the initial table is generated:
// List current equipment...
$query = "SELECT eq_type_id, eq_name, asset_no, description ".
"FROM joEquipment LEFT JOIN eqTypes USING(eq_type_id) ".
"WHERE job_id = $job_id";
$result = mysql_query($query, $link);
if(mysql_num_rows($result) < 1)
echo "<p>No equipment added yet.</p>\n";
else
{
echo "<table id='equip' class='mini'>\n";
// This header row should be row 0...
echo "<tr id='eqHead'>\n";
echo "<td class='hd'>Equipment Type</td><td class='hd'>Asset #</td><td class='hd'>Description</td>\n";
echo "</tr>\n";
$x = 1;
// Output rows 1 through the nth row...
while($row = mysql_fetch_assoc($result))
{
// Select box of equipment types...
echo "<tr><td><select name='eq_type_id[]'>\n";
foreach($eq_types as $id => $name)
{
$sel = "";
if($row['eq_type_id'] == $id)
$sel = "selected";
echo "<option value='$id' $sel>$name</option>\n";
}
echo "</select></td>\n";
echo "<td><input type='text' name='asset_no[]' value='".$row['asset_no']."' size='20' maxlength='20' /></td>\n";
echo "<td><input type='text' name='description[]' value='".$row['description']."' size='60' maxlength='90' />";
// The remove button...
echo "<input type='button' name='rmv$x' value='remove' onclick='delEquip($x)'></td></tr>\n";
$x++;
}
echo "</table>\n";
}
And of course, the addEquip button...
<input type="button" name="addeq" value="+ Add Equipment" onclick="addEquip()" />
Any clues?