Ok I've fixed your issue. You don't need .parent()
or .closest()
. You simply needed to retain a reference to your top level container and then based on the extraction of the id on the button that was clicked, you can simply remove all children of the container that end with that id number.
Here's what I did:
$('#AddCC').click(function () {
uniqueId++;
var container = $("#CCcontainer"),
copyDiv = $("#CCPanel").clone(),
divID = "CCPanel" + uniqueId,
removeID = "RemoveCard" + uniqueId;
copyDiv.attr('id', divID);
container.append(copyDiv);
container.append("<div id =" + removeID + " ><div class =\"form-group col-sm-10\"></div><div class =\"form-group col-sm-2\"><button id=\"btn" + removeID + "\" type=\"button\" class=\"btn btn-warning form-control\">Remove Card</button></div></div>");
$('#' + divID).find('input,select').each(function () {
$(this).attr('id', $(this).attr('id') + uniqueId);
});
$("#" + removeID).find("button").on("click", function () {
var id = $(this).attr("id").replace("btnRemoveCard", "");
container.find("div[id$='" + id + "']").remove();
});
});
UPDATE
The fiddle now has been updated to include code that will save the unique ids of the panels that are used. It includes a hidden input field that simply stored an array of the ids. It's defaulted to 1 since the first panel is already on the screen.
<input id="hiddenStoredPanelsArray" type="hidden" value="[1]" />
In the updated JavaScript you'll notice that I left console.log
statements in there so you can see what happens to the array as you add and remove panels.
$('#AddCC').click(function () {
uniqueId++;
var container = $("#CCcontainer"),
hidden = $("#hiddenStoredPanelsArray"),
storedPanels = hidden.length ? $.parseJSON(hidden.val()) : null,
copyDiv = $("#CCPanel").clone(),
divID = "CCPanel" + uniqueId,
removeID = "RemoveCard" + uniqueId;
console.log(storedPanels);
storedPanels.push(uniqueId);
hidden.val(JSON.stringify(storedPanels));
console.log(storedPanels);
copyDiv.attr('id', divID);
container.append(copyDiv);
container.append("<div id =" + removeID + " ><div class =\"form-group col-sm-10\"></div><div class =\"form-group col-sm-2\"><button id=\"btn" + removeID + "\" type=\"button\" class=\"btn btn-warning form-control\">Remove Card</button></div></div>");
$('#' + divID).find('input,select').each(function () {
$(this).attr('id', $(this).attr('id') + uniqueId);
});
$("#" + removeID).find("button").on("click", function () {
var id = parseInt($(this).attr("id").replace("btnRemoveCard", "")),
hidden = $("#hiddenStoredPanelsArray"),
storedPanels = hidden.length ? $.parseJSON(hidden.val()) : null,
index = storedPanels == null ? -1 : storedPanels.indexOf(id);
console.log(storedPanels);
if (index > -1)
storedPanels.splice(index, 1);
console.log(storedPanels);
container.find("div[id$='" + id.toString() + "']").remove();
hidden.val(JSON.stringify(storedPanels));
});
});