Disabling input boxes with setTimeout

75 Views Asked by At

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);
2

There are 2 best solutions below

1
j-0-n-e-z On BEST ANSWER

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>

2
bosscube On

I'm not really sure what you're trying to do exactly, but am I close?

const options = document.querySelector('.options');
const lockableInputs = options.querySelectorAll('.lockable-input');

options.addEventListener('change', e => {
  const { target } = e;
  
  if (!target.closest('.lockable-input')) return;
  
  e.preventDefault();
  
  if (!target.checked) return;
  
  lockableInputs.forEach(input => input.disabled = true);

  setTimeout(() => {
    lockableInputs.forEach(input => input.disabled = false);
  }, 2000);
});