skip to Main Content

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

3

Answers


  1. I am not sure about the rest of your code since you haven’t provided the html and CSS files.
    Anyways reading your code, and using customId as a string rather than as a variable could be the problem, if everything else is fine.

    document.getElementById('customid').style.display = "block";
    

    try changing this to

    document.getElementById(customid).style.display = "block";
    

    do the same for the display = "none" case

    Login or Signup to reply.
  2. It looks like there might be an issue with how you’re trying to set the display property based on the checkbox state. Also, there is an issue with the way you’re trying to set the ID of the dynamically created div.
    Try this:

    Use event.target to get the clicked checkbox element inside the event handler.

    Remove the unnecessary check for checkbox state (if (FilterDropdownsElem[i].checked == true)) because it’s redundant.

    Use div.remove() to remove the dynamically created div when the corresponding checkbox is unchecked.

    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 = FilterDropdownsElem[i].id + i; // Use a simpler customid
        
        FilterDropdownsElem[i].addEventListener('click', function (event) {
            let checkbox = event.target;
            let divId = checkbox.id + i;
            let div = document.getElementById(divId);
    
            if (checkbox.checked) {
                // If the checkbox is checked, create the div if it doesn't exist
                if (!div) {
                    ChoosenFiltercontainer.innerHTML += `<div class="col-md-auto" id="${divId}">
                        <div class="chip chip-outline btn-outline-dark rounded-pill" data-mdb-ripple-color="dark">
                            ${checkbox.id} <i class="close fas fa-times" style="font-size: small;"></i>
                        </div>
                    </div>`;
                }
            } else {
                // If the checkbox is unchecked, remove the corresponding div
                if (div) {
                    div.remove();
                }
            }
        });
    }
    
    
    Login or Signup to reply.
  3. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search