javascriptsettimeoutcleartimeout

Disabling input boxes with setTimeout


I have some input boxes that I want to disable for a few seconds if one is clicked.

I am using setTimeout and disabled property to make the check boxes un-clickable. Then I would like to use clearTimeout to make it clickable again after moments have passed.

Two issues I'm running into:

  1. If I click one box, it only disables the first checkbox. I'm assuming it's because it only disables the first checkbox with the id='test' But if I change it to getElementsByClassName the disabled doesn't work.
  2. The clearTimeout is just not working.

Here is a jsfiddle. You can comment out lines 6-8 in the Javascript section to see how the disableClick() function works with an ID, but only disables Digital Filter.

Here is my HTML:

<input id="test" type="checkbox" value="digital-filter" onclick="setTimeout(disableClick, 500)">
<span>Digital Filter</span>
<input id="test" type="checkbox" value="meter" onclick="setTimeout(disableClick, 500)">
<span>Meter</span>

Here is my javascript:

var subfilters;
function disableClick(){
    subfilters = document.getElementById("test").disabled = true;
}

setTimeout(() => {
  clearTimeout(subfilters);
}, 250);

Solution

  • You may try something simpler, without clearTimeout.

    const tests = document.querySelectorAll('.test')
    const form = document.querySelector('.filters')
    
    form.addEventListener('change', e => {
      e.preventDefault()
      
      // you may add this line to disable intputs only when you check
      if (!e.target.checked) return
      
      tests.forEach(test => test.disabled = true)
      setTimeout(() => tests.forEach(test => test.disabled = false), 500)
    })
    <form class='filters'>
      <label>
        <input class="test" type="checkbox" value="digital-filter">
        Digital Filter
      </label>
      <label>
        <input class="test" type="checkbox" value="meter">
        Meter
      </label>
    <form>