JSFiddle - React, Tailwind, and code Playground

by houssamk

HTML

<div id='main'>
    <p style='color:yellow'>Top paragraph</p>
    <p>Item 1 - Apple 5$
        <input name="one" type="checkbox" value="Apple 5$" />
    </p>
    <p>Item 2 - Orange 6$
        <input name="two" type="checkbox" value="Orange 6$" />
    </p>
    <p>Item 3 - Tomatoe 3$
        <input name="anything_unique" type="checkbox" value="Tomatoe 3$" />
    </p>
    <p style='color:yellow'>Bottom pragraph</p>
</div>

CSS

p {
    background-color:red;
    margin:10px
}

JavaScript

var i = 0; // private object. this counter is shared for all checkboxes

var bindFunction = function () { // private object / function
    var $this = $(this); // the current target, the checkbox which we just clicked
    var oldName = $this.attr('name'); // get the current name 
    var lastIndexOf_ = oldName.lastIndexOf('_');
    // we build the clones with and underscore + number. get substring from the beginning of the oldName until the "_"
    if (lastIndexOf_ != -1)
        oldName = oldName.substring(0,lastIndexOf_);
    // else just use the oldName
    var newName = oldName + '_' + i++; // build new name and increment counter.
    var $cloneParagraph = $this.parent().clone(); // clone paragraph
    var $cloneCheckbox = $cloneParagraph.find('input:checkbox'); // clone checkbox
    $cloneCheckbox.attr('name', newName); // set new name on the clone checkbox
    alert(newName);

    if ($this.is(':checked')) {
        $cloneCheckbox.prop('checked', false); // uncheck clone
    } else {
        $cloneCheckbox.change(); // trigger change event
    }

    $cloneParagraph.insertBefore($(this).parent()); // insert new content before the current checkbox
};


$('#main').on('change', 'input:checkbox', bindFunction); // "$.on" attaches the event hadndler dynamically when an input:checkbox gets created under the main div. so there is no need to attach it within the bind function. instead of calling the bind function from iwthin its definition, all we have to do is call .change()