Good afternoon, there are several checkboxes, the task is to create a div-box with the name corresponding to the checked checkbox when clicking on the checkbox below. I tried to do, when clicking on one checkbox, a line is created as expected, but if you click on the second, then another 2 lines are created, that is, a line for each checkbox that is checked, please tell me what I am doing wrong Also, if you disable the checkbox, the line should be deleted.
$(".option-item input").on("change", function(){ addCheckOption(); }); function addCheckOption() { $(".option-item input").each(function () { var optionTitle = $(this).data('name'); var optionList = document.getElementById('check-option-block'); var optionItem = document.createElement('div'); var optionNameBlock = document.createElement('div'); var optionName = document.createTextNode(optionTitle); optionNameBlock.className = 'option-name-block col-sm-9 col-xs-12 '; optionItem.className = 'option-block-row row'; if ($(this).is(":checked")) { optionNameBlock.appendChild(optionName); optionItem.appendChild(optionNameBlock); optionList.appendChild(optionItem); } else { $(optionItem).remove(); } }); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="option-item"> <input type="checkbox" id="check1" data-name='Питер'/> <label for="check1"><span></span><strong id='test'>Питер</strong></label> </div> <div class="option-item"> <input type="checkbox" id="check2" data-name='Москва'/> <label for="check2"><span></span><strong>Москва</strong></label> </div> <div id="check-option-block"></div>