MegaTron MegaTron - 4 months ago 38
jQuery Question

How to clone similar element when checkbox change using jquery?

I currently have a number of items each with a list of data inside. What I'm trying to achieve is, when i select a checkbox that has the same matching attribute of

itemName
, the matching div that contains the additional data is appended to a container. I have written some code up here:

<div class="item" itemName="itemOne">
<h2> Item One </h2>
<ul>
<li> Data 1 </li>
<li> Data 2 </li>
<li> Data 3 </li>
</ul>
</div>
<div class="item" itemName="itemTwo">
<h2> Item Two </h2>
<ul>
<li> Data 1 </li>
<li> Data 2 </li>
<li> Data 3 </li>
</ul>
</div>
<ul class="itemSelection">
<li itemName="itemOne">
<label><input type="checkbox"/>Item One</label>
</li>
<li itemName="itemTwo">
<label><input type="checkbox"/>Item Two</label>
</li>
</ul>
<div id="container"></div>


Any help would be greatly appreciated.

Answer

You need to check state of checkbox. If checkbox is checked use .appendTo() to adding target element to #container and if it is unchecked use .remove() to deleting it.

$(".itemSelection :checkbox").change(function(){
    var itemName = $(this).closest("li").attr("itemName");
    if (this.checked)
        $(".item[itemName=" + itemName + "]").clone().appendTo("#container");
    else
        $("#container .item[itemName=" + itemName + "]").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item" itemName="itemOne">
    <h2> Item One </h2>
    <ul>
        <li> Data 1 </li>
        <li> Data 2 </li>
        <li> Data 3 </li>
    </ul>
</div>
<div class="item" itemName="itemTwo">
    <h2> Item Two </h2>
    <ul>
        <li> Data 1 </li>
        <li> Data 2 </li>
        <li> Data 3 </li>
    </ul>
</div>
<ul class="itemSelection">
    <li itemName="itemOne">
        <label><input type="checkbox"/>Item One</label>
    </li>
    <li itemName="itemTwo">
        <label><input type="checkbox"/>Item Two</label>
    </li>
</ul>
<div id="container"></div>

Comments