dynamic checkbox list in html

Solutions on MaxInterview for dynamic checkbox list in html by the best coders in the world

showing results for - "dynamic checkbox list in html"
Andrea
17 Feb 2018
1
2const DynamicCheckboxes = {
3  checkboxes: document.querySelectorAll('.table td input[type="checkbox"]'),
4  selectAllTarget: document.querySelector('.js-select-all'),
5  clearBtn: document.querySelector('.js-clear'),
6
7  initialize() {
8    this.shiftToSelect();
9    this.selectAll();
10    this.clearChecked();
11    this.showRemoveCheckedButton();
12  },
13
14  shiftToSelect() {
15    const checkboxes = this.checkboxes;
16    let lastChecked;
17
18    function handleCheck(event) {
19      // Check if shift key is down and check if checkbox is checked
20      let inBetween = false;
21      if (event.shiftKey && this.checked) {
22        checkboxes.forEach(checkbox => {
23          if (checkbox === this || checkbox === lastChecked) {
24            inBetween = !inBetween;
25          }
26
27          if (inBetween) {
28            checkbox.checked = true;
29          }
30        });
31      }
32      lastChecked = this;
33    }
34
35
36    checkboxes.forEach(checkbox => checkbox.addEventListener('click', handleCheck, false));
37  },
38
39  selectAll() {
40    function handleSelectAll(event) {
41      this.checkboxes.forEach(checkbox => {
42        checkbox.checked ? (checkbox.checked = false) : (checkbox.checked = true)
43      })
44    }
45
46    this.selectAllTarget.addEventListener('click', handleSelectAll.bind(this), false)
47  },
48
49  showRemoveCheckedButton() {
50    this.clearBtnDisplay('none')
51    document.addEventListener('change', this.showBtn.bind(this))
52  },
53
54  showBtn(event) {
55    const checkboxesChecked = document.querySelectorAll('.table td input[type=checkbox]:checked').length
56
57    if (checkboxesChecked > 0) {
58      this.clearBtn.querySelector('span').textContent = checkboxesChecked;
59      this.clearBtnDisplay('block');
60    } else {
61      this.clearBtn.querySelector('span').textContent = '';
62      this.clearBtnDisplay('none');
63    }
64  },
65
66  clearBtnDisplay(state) {
67    this.clearBtn.style.display = state;
68  },
69
70  clearChecked() {
71    this.clearBtn.addEventListener('click', removeChecked.bind(this), false);
72
73    function removeChecked() {
74      this.checkboxes.forEach(checkbox => (checkbox.checked = false));
75      this.selectAllTarget.checked = false;
76      this.clearBtnDisplay('none');
77    }
78  }
79
80};
81
82DynamicCheckboxes.initialize();
83