ClosDesign
ClosDesign

Reputation: 3924

Reappend a removed item in jQuery

I am populating a separate list with items from a bunch of checkboxes using jQuery.

I am able to append and remove the list items if there is a check or uncheck. The issue I am having is when I use the .remove(), if I try to go and re-append a list item, there is no action. The list item does not get re-appended.

Below is my jQuery I am using, but what would be logic to get it to re-append after a list item has been removed.

   $('#attendeePicker .zInput.zCheckbox ,#attendeePicker2 .zInput.zCheckbox').on("click", function(e) {
            var parentSection = $(this).parents("section").attr("id");


            var attendeename = $(this).find('input').data("attendeename"),
                productname = $(this).find('input').data("productname"),
             optionprice = $(this).find('input').data("optionprice"),
                /* get jQuery selector for list from data */
                //jQId = "#" + data.,
                $list = $(".CartList li." + attendeename).find('.itemList');
            //alert($list)


            if ($(this).hasClass("zSelected")) {
                /* add element to list if selelected*/

                var li = '<li class="animated bounceIn"><span class="itemTime">' + $("#" + parentSection + " .timelist .zInput.zSelected input").val() + ' - ' + '</span><span class="itemName">' + productname + '</span><span class="itemPrice">' + optionprice + '</span></li>';
                //  var li = '<li class="animated bounceIn"><span class="itemTime">' + $(".timelist .zInput.zSelected input").val() + ' - ' + '</span><span class="itemName">' + productname + '</span><span class="itemPrice">' + optionprice + '</span></li>';

                $list.append(li);

            } else {
                /* empty list if unchecked*/

                //Empties the ilist BUT we don't want that.
                // $list.empty(); // completely empties the list
                $list.remove(li);  //only removes the single item. I want this.

            }

        });  

Upvotes: 0

Views: 794

Answers (2)

hityagi
hityagi

Reputation: 5256

When you remove an element it is removed from the DOM so you cannot re append it.

You can do it in following ways :

Method 1

Clone the element (.clone()) first and then remove it. Use the cloned object to re-append.

WORKING SAMPLE : http://jsfiddle.net/pvod0gam/1/

var $elem;
$("#check").click(function(){
    if($(this).prop("checked")){
        $elem = $("#elem").clone();
        $("#elem").remove();
    }else{
        $("body").append($elem);
    }
});

Method 2

Toggle display of the element (.toggle()). Basically show/hide on checkbox state.

WORKING SAMPLE : http://jsfiddle.net/9mfv67gq/

$("#check").click(function(){
    $("#elem").toggle();
});

Upvotes: 1

C Bauer
C Bauer

Reputation: 5103

Just .hide() and .show() the sub list based on the checkbox that you are checking/unchecking.

Upvotes: 0

Related Questions