I have two textboxes and an add button. When you click add it generates a table below the textboxes with each row having a Remove button. When you click remove it removes the table row but doesn’t remove the contents from within the array (at least i don’t think).
How do I get it to remove the contents as well? Currently when I click add and then remove a few it messes up my database table by inserting the first one fine but then messing up the rest by either not inserting it, or just adding 1 column…. If i don’t remove any it works perfectly fine.
var $tdRemoveRow = $('<td>').appendTo($tr);
$('<a>').attr({
'href': '#',
'id': 'submit-button'
}).text("Remove").click(function() {
$tr.remove();
return false;
}).appendTo($tdRemoveRow);
The error must be in the above code somewhere. Does anyone see an issue?
var locations = [];
$("#add").click(function() {
var address = $("#address").val();
var city = $("#city").val();
if (address =="" || city =="") {
$("#locationDeals").text('*Please enter an address and city');
return false;
}
else {
codeAddress();
var $tr = $('<tr>').css({
'padding': '4px',
'background-color': '#ddd'
}).appendTo('#locationDeals');
var location = [
address,
city
];
locations.push(location);
for (i = 0; i < 2; i++) {
var $td = $('<td>').appendTo($tr);
$('<span>').text(location[i]).appendTo($td);
$('<input type="hidden">').attr({
'name': 'loc[' + ctr + '][' + i + ']',
'value': location[i]
}).appendTo($td);
}
var $tdRemoveRow = $('<td>').appendTo($tr);
$('<a>').attr({
'href': '#',
'id': 'submit-button'
}).text("Remove").click(function() {
$tr.remove();
return false;
}).appendTo($tdRemoveRow);
ctr++;
$("#locationtext").text('');
return false;
}
});
When removing the row, use
.spliceto also remove it from the array:Note that this will not behave correctly if
locationis not insidelocations, but with your code this is guaranteed not to be the case.You shuold decrement the indices in the input names as well (just before removing the
tr):