1

I am adding a button using append. How can find its parent div id (removeID) value so I can remove only that particular section?

$("#CCcontainer").append("<div id ="+removeID +" ><div class =\"form-group col-sm-10\"></div><div class =\"form-group col-sm-2\"><button type=\"button\" id=\"removeCard\"  class=\"btn btn-warning form-control\">Remove Card</button></div></div>");

$(document).on('click','#removeCard',function () 
{
    uniqueId--;
    alert("Removing" +("#CCPanel" + uniqueId) );

    $("#CCPanel" + uniqueId).remove();
    $("#removeCard"+ uniqueId).remove();
});

The above code is removing the button always from bottom. If I clicked on remove button in the middle, last one is getting deleted. I am trying to see if I can track the id of the clicked button so I can remove only that specific section.

Is there any way I can always maintain the sequence order? Like if I add 4 sections and removed second and then add one more time I should see sequence 4 not 5.

Go to my jsFiddle and click [Add Another Card button] (Orange Button) to see how it works.

Code Maverick
  • 19,231
  • 10
  • 57
  • 111
user3067524
  • 507
  • 3
  • 9
  • 24
  • please look below thread >http://stackoverflow.com/questions/545978/finding-the-id-of-a-parent-div-using-jquery – java seeker Jan 24 '14 at 18:37
  • parent or closet both are not working. Please help. – user3067524 Jan 24 '14 at 19:00
  • do you use firebug? can you please check what is happening through firebug – java seeker Jan 24 '14 at 19:18
  • Actually I solved the problem. I have updated the HTML in append by adding an id for parent div tag and using parent method. Fiddle updated. But i still have another question. How can maintain the sequence ?http://jsfiddle.net/tK4f6/14/ – user3067524 Jan 24 '14 at 19:28
  • @user3067524 - I fixed your issue right before you posted this. I've optimized your code and it maintains sequence. Take a look: http://stackoverflow.com/a/21339821/682480. – Code Maverick Jan 24 '14 at 19:48

2 Answers2

1

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();
    });
});

See working jsFiddle demo

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));
    });
});
Code Maverick
  • 19,231
  • 10
  • 57
  • 111
  • Any sample code please ? I used closet for now but geting undefined. I would like to try using parent but need a sample. http://jsfiddle.net/tK4f6/13/ – user3067524 Jan 24 '14 at 18:44
  • Thank you for your time and I appreciate you rhelp. I think I still see a small issue. I have added 4 times, removed second seaction then added again and try to remove the last one that I have added. But nothing is happening. – user3067524 Jan 24 '14 at 20:05
  • I have tested again to make sure I see correct. Yes If you add couple of times and remove one in between and then add, the one we added last cannot be deleted. But by clicking other remove button, don't know exactly, removing two sections at a time i guess. – user3067524 Jan 24 '14 at 20:11
  • @user3067524 - Ok, I've fixed the bug. I just needed to remove the `uniqueId--;` from the remove card button click. Now you can add 2,3,4, remove 3, leaving 1,2,4, add 5,6,7, remove 6, leaving 1,2,4,5,7. That's how you wanted it, yes? – Code Maverick Jan 24 '14 at 20:21
  • Can 1,2,4,5,7 becomes 1,2,3,4,5 ? Thanks! – user3067524 Jan 24 '14 at 20:29
  • @user3067524 - Can you explain why that's needed? Why rename ids on controls that are already on the page? They are still in order. There's nothing on the page that uses that number visually that I can see. – Code Maverick Jan 24 '14 at 20:31
  • Sure. Finally when submit, on server, I can look for ex : CCname1, CCName2 etc. if section 1 removed I may not get value for that. – user3067524 Jan 24 '14 at 20:35
  • @user3067524 - Right, but why would you be going in numerical order versus looping through the actual existing objects? Or do what I did in the click handler. Simply remove the prefix of the control and you have the `uniqueId` that was used. – Code Maverick Jan 24 '14 at 20:41
  • on server request.getParameter("?????"); not knowing 1 or 2 how can I get the value of that element ? – user3067524 Jan 24 '14 at 20:45
  • I am thinking to submit the whole form to server. If you think there would be anothe ridea or sequencing correct before submiting that would be great! – user3067524 Jan 24 '14 at 20:46
  • @user3067524 - You wouldn't know the number no matter if they were in order or not, right? I would just submit the whole form to the server. If you don't want to do that, you could create a hidden input that contains a string array that holds all the ids. You add the id in the add click and you remove the id in the remove click. Then you call your getParameter for the array field, parse, and now you have the ids to use for getting the specific controls. – Code Maverick Jan 24 '14 at 20:51
  • I like the hidden input idea. But I may need your help on how to add and remove id's to that. Thank you! – user3067524 Jan 27 '14 at 20:01
  • @user3067524 - I'll try to help you when I get a chance. – Code Maverick Jan 27 '14 at 20:07
  • @user3067524 - Ok, answer has been updated. I hope you like it. All you should need to do now is post that hidden input field, parse it on the server, and you have your unique ids that you can use to pull each specific panel and their elements. – Code Maverick Jan 27 '14 at 22:09
  • Awesome!!!!. Thank you verymuch. Really great help. You sepnt lot of time on this. I really appreciate it.Again Thank you. My Best Regards. – user3067524 Jan 28 '14 at 14:20
  • HI, Can you explain me below two lines when you get a chance?index = storedPanels == null ? -1 : storedPanels.indexOf(id);container.find("div[id$='" + id.toString() + "']").remove(); - what is "id$ do in find method? – user3067524 Jan 28 '14 at 21:05
  • @user3067524 - The first line checks to make sure `storedPanels` has a value. If not, it sets `index = -1`. If it has a value, it retrieves the `index` of the `id` in the `storedPanels` array. – Code Maverick Jan 28 '14 at 21:07
  • @user3067524 - The second line searches the `container` object for all divs ending with the id of `id.toString()` and then consequently removes them from the DOM. So to answer your question, `id$=`, means `id ending with`. If it were `id^=` it would be search for an `id beginning with`. It's regular expression syntax. – Code Maverick Jan 28 '14 at 21:09
  • @user3067524 - Oh ... and you can always *upvote* any answer that helps you to show your appreciation. I know I would be appreciative of your appreciation =D – Code Maverick Jan 29 '14 at 18:10
  • Hi there, Today I found a performance issue. I am using IE 9. Once i have mu hope page up, if i click addAnother card button, it it not responding for at least 8 to 10 sec. if I click again after 10 sec, then addButton is working.This is happening only firsttime when application opened firttime and then click the AddButton. Any suggetions please? Thanks! – user3067524 Feb 05 '14 at 13:34
  • I have posted new question on this. http://stackoverflow.com/questions/21579276/jquery-clone-performnace-issue?noredirect=1#comment32596867_21579276 – user3067524 Feb 05 '14 at 14:05
0

I think what fits best (if I understand) to its context is the closest function, it gets the first parent that matches the passed selector

.closest("#removeId");
Code Maverick
  • 19,231
  • 10
  • 57
  • 111
Paulo Lima
  • 1,244
  • 8
  • 8