0

What I'm trying to achieve

  • Clone a div and add it below the existing div(s) - jQuery 1 below
  • ...in the div that is being cloned, I already have another jQuery running that shows/hides a child div based on a checkbox - jQuery 2 below

Issue Cloning works fine. However, I can't get the show/hide based on checkbox to work

Question Is this possible to do through jQuery? It seems like jQuery 2 doesn't understand that, post-cloning, there's a new div that also would like the same functionality of showing/hiding the child-div based on the checkbox.

jQuery 1

$(document).ready(function() {
  var i = 0;
    $('.button-add').click(function(){
        $i = i++;
        //we select the box clone it and insert it after the box
        $copy = $('.copybox:first').clone();
        $copy.find("input:checkbox").attr("data-related-item","hideconfig"+i);
        $copy.find("div#hideconfig").attr("id","hideconfig"+i);
        $copy.insertAfter(".copybox:last");
    });

    $(document).on("click", ".button-remove", function() {
        $('.copybox:last').remove();
    });
});

jQuery 2

function evaluate(){
    var item = $(this);
    var relatedItem = $("#" + item.attr("data-related-item"));

    if(item.is(":checked")){
        relatedItem.fadeIn();
    }else{
        relatedItem.fadeOut();   
    }
}

$('input[type="checkbox"]').click(evaluate).each(evaluate);
daxro
  • 193
  • 13
  • This is similar but in my opinion NOT a full true duplicate and can be resolved using `$copy = $('.copybox:first').clone(true,true);` and then alternately `$(document).on('click','input[type="checkbox"]',evaluate).each(evaluate);` – Mark Schultheiss Nov 04 '15 at 12:28
  • Mighty Mark - thanks! ^^ – daxro Nov 04 '15 at 12:41
  • NOTE: when you clone you likely do NOT want to keep track of a global `i` this way but instead, get the length (count) of the `.copybox` elements and then use that as the "current" basis for an element attribute - OR alternately, put that value in a data on some wrapper and use that, hard to tell without the markup for sure but avoids page refresh issues. You could get the max of any of those somehow by query of each etc. inside that click for the add button...OR use the index of the element you are adding via clone as the basis instead of trying to add a new id this way. – Mark Schultheiss Nov 04 '15 at 16:48

0 Answers0