vendredi 3 juillet 2020

removing cloned element if a checkbox is unchecked with JQuery in a bootstrap 4 form

So, I am building this prototype using Bootstrap 4 and jQuery. I am using some of its built-in classes. I have a bunch of checkboxes in a modal that when clicked, must be added into a drop down list outside of the modal. This is how the checkboxes look in the html:

<div class="form-group checkbox">
 <label>
   <input id="cbitem_Premium_Rate" type="checkbox" class="enableInput" onclick="pass2Dropdownlist(this.id);">
   <span class="cb"><i class="cb-icon fa fa-check"></i></span>
   <span class="cb-text">Premium %</span>
 </label>
 <errormsg></errormsn>
</div>

To add the checked item into the dropdown list, I clone the a tag with the id "dditem_template" with a new id, and append it into the div tag:

<div class="btn-group" role="group">
<button id="btnGroupDrop1" type="button" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></button>
  <div id="dd_itemsSelected" class="dropdown-menu" aria-labelledby="btnGroupDrop1">
    <a id="dditem_template" class="dropdown-item d-none" href="#">Item Selected</a>
    <a id="dditem_null" class="dropdown-item d-none" href="#">No options selected.</a>
  </div>
</div>

and this is the function pass2Dropdownlist(this.id) :

function pass2Dropdownlist(id){
 
 var newID = id.replace("cbitem", "dditem");
 if($(this).find(':checkbox').prop("checked", true)){

   var ddName = id.replace("cbitem", "");
   var ddName = ddName.replace("_", "");
   ddName = replaceAll(ddName, "_", " ");

   var listItem = $("#dditem_template").clone();

   listItem.each(function(){
    $(this).attr('id', newID);
    $(this).text(ddName);
   });

   $("#dd_itemsSelected").append(listItem);
   listItem.removeClass("d-none");
   listItem.addClass("addeditem");
   $("#dditem_null").addClass("d-none");

 }else{
   $("#" + newID).remove();
 }
}

My problem is that if I unchecked the checkbox the item in the dropdown list doesn't get removed... instead, it gets added again. It's as if is never entering the else portion of the if statement. Why? am I missing something in the else statement? I will appreciate a lot your help!!




Aucun commentaire:

Enregistrer un commentaire