How to fix this multi-select checkbox issue?

Dear all, I’m developing a simple 3-selelct checkbox, function:
1 The initial stage: 3 parameters have already been selected, the other boxes are disabled
2 If cancel any of these 3 selected boxes, the other boxes are enabled, and can select up to 3 boxes.

currently the issue is: if the initial stage is 3 paras selected, the other boxes can be disabled until another (the 4 th) box is selected. However, if the initial stage is 2-selected, the function works. But I still want to keep 3-selected as a initial stage. Would you please tell me the bug inside my codes?

How to fix this multi-select checkbox issue

Would it be the issue of ‘onchange’ function, because I need to make a ‘change’, which is ticking the checkbox first, so that the function could work. I was wondering is there any other function not to detect the ‘change’, but to detect the ‘condition’?

The problem is that you forgot the initialization (happens often with event handlers). Simply call your handler once where/when you attach it:

function limitCheckboxes(limit, widget)
  widget.addEventListener('change', onchange);
  return widget;
  function onchange() {
    const checked = widget.querySelectorAll('input[type="checkbox"]:checked');
    const unchecked = widget.querySelectorAll('input[type="checkbox"]:not(:checked)');
    for(const n of unchecked) n.disabled = checked.length >= limit;
1 Like

Thank you very much Mootari!