Search code examples
javascriptjquerycheckboxcheckedoncheckedchanged

How do I convert this jquery to pure javascript?


Hello I want to convert the following to pure JS if possible.

My ultimate goal is to display the var "bar" if checkboxes with id's ("checkbox1", "checkbox2", "checkbox3") are selected + display corresponding id's ("item1", "item2", "item3").

$('input:checkbox').change(function () {
    if ($(this).is(':checked')) {
        switch (this.id){
            case 'checkbox1':
                bar.show();
                item1.show();
                break;
            case 'checkbox2':
                bar.show();
                item2.show();
                break;
            case 'checkbox3':
                bar.show();
                item3.show();
                break;
            default:
                bar.hide();
        }
    } else {
        bar.hide();
    }
});

How can i simply do this?


Solution

  • Try this code example.

    const ids = ["item1", "item2", "item3"]
    
    document.addEventListener("change", function(event) {
      if (event.target.matches('input[type="checkbox"]')) {
        const checkboxes = document.querySelectorAll('input[type="checkbox"]')
        let checked = []
        
        checkboxes.forEach(function (cb) {
          if (cb.checked) checked.push(cb)
        })
          
        const checkedIds = checked.map(cb => cb.id)
        
        if (isSubArray(ids, checkedIds)) {
          document.querySelector("#var").style.display = "block"
        } else  {
          document.querySelector("#var").style.display = "none"
        }
        
        document.querySelector("#cb-ids").innerHTML = checkedIds
      }
    })
    
    function isSubArray(arr1, arr2) {
      return arr1.every( el => arr2.includes(el))
    }
    <p id="var" style="display: none">var</p>
    
    <p id="cb-ids"></p>
    
    <label for="item1"> 
      <input id="item1" type="checkbox" />
       Item 1 
    <label/>
    <label for="item2"> 
      <input id="item2" type="checkbox" />
       Item 2 
    <label/>
    <label for="item3"> 
      <input id="item3" type="checkbox" />
       Item 3
    <label/>
    <label for="item4"> 
      <input id="item4" type="checkbox" />
       Item 4
    <label/>