javascripthtmlbootstrap-4innerhtml

How do i add html element from javascript


I was trying to create a chip when a checkbox is checked by adding an eventlistener function to the checkbox but it is not happening . I think the element is not being inserted to the html . Here is the code

let ChoosenFiltercontainer = document.getElementById('ChoosenFiltercontainer')
let FilterDropdownsElems = document.querySelector('.FilterDropdowns');
let FilterDropdownsElem = FilterDropdownsElems.querySelectorAll('[type=checkbox]');
let customid = "";
for (let i = 0; i < FilterDropdownsElem.length; i++) {
  customid = customid + FilterDropdownsElem[i].id + i;
  FilterDropdownsElem[i].addEventListener('click', function(customid) {
    ChoosenFiltercontainer.innerHTML += `<div class="col-md-auto " id=${customid}  style="display:none;" >
          <div class="chip chip-outline btn-outline-dark rounded-pill" data-mdb-ripple-color="dark">
            ${FilterDropdownsElem[i].id} <i class="close fas fa-times" style="font-size: small;"></i>
          </div>
        </div>`;
    if (FilterDropdownsElem[i].checked == true) {
      document.getElementById('customid').style.display = "block";
    } else {
      document.getElementById('customid').style.display = "none";
    }
  }.bind(this, customid))
}    

I think that i am not using the innerHTML property correctly


Solution

  • I always suggest delegation so I will refactor instead of debugging your code which has some strange statements, like your .bind

    Here is a version that delegates from the filterDropdown container and the ChoosenFiltercontainer

    I added the checkbox ID to the close as a data attribute so we can uncheck the filter if we close it

    const ChoosenFiltercontainer = document.getElementById('ChoosenFiltercontainer');
    document.querySelector('.FilterDropdowns').addEventListener('click', (e) => {
      const tgt = e.target;
    
      if (!tgt.matches("input[type=checkbox]")) return;
      let elementId = `${tgt.id}_container`; // Create a unique ID for the container
      let filterElement = document.getElementById(elementId);
      if (!filterElement) {
        console.log('creating div');
        ChoosenFiltercontainer.innerHTML += `<div class="col-md-auto filter" id="${elementId}" style="display: none;"><div class="chip chip-outline btn-outline-dark rounded-pill" data-mdb-ripple-color="dark">${tgt.id} <i data-id="${tgt.id}" class="close fas fa-times" style="font-size: small;"></i></div></div>`;
        filterElement = ChoosenFiltercontainer.lastChild;
      }
      filterElement.style.display = tgt.checked ? 'block' : 'none';
    });
    ChoosenFiltercontainer.addEventListener('click', (e) => {
      const tgt = e.target;
      if (tgt.matches('i.close')) {
        const filterId = tgt.dataset.id;
        document.getElementById(filterId).checked = false;
        tgt.closest('div.filter').style.display = 'none';
      }  
    });
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" integrity="sha512-z3gLpd7yknf1YoNbCzqRKc4qyor8gaKU1qmn+CShxbuBusANI9QpRohGBreCFkKxLhei6S9CQXFEbbKuqLg0DA==" crossorigin="anonymous" referrerpolicy="no-referrer"
    />
    
    <div id="ChoosenFiltercontainer">
      <!-- Selected filters will be displayed here -->
    </div>
    
    <div class="FilterDropdowns">
      <!-- Example checkboxes -->
      <label><input type="checkbox" id="filter1">Filter 1</label>
      <label><input type="checkbox" id="filter2">Filter 2</label>
    
    </div>