-1

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?

2 Answers2

0
  1. In order to select an HTML element, you can use the document class methods (e.g. document.getElementsByTagName).
  2. As written in jQuery's documentation, show() and hide() actually modify the display attribute of an HTML element.
GalAbra
  • 5,048
  • 4
  • 23
  • 42
  • thanks for your answer! I do want to move away from jQuery and want to write everything with pure JS. Is that possible with css pseudo classes? And what would the if/else statement look like? – jimmyinthenetherlands Apr 11 '20 at 13:37
0

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/>
gedhean
  • 112
  • 4