Home > Software design >  can't block fields when check button is checked
can't block fields when check button is checked

Time:03-21

I created function where I block all my inputs( I did it with for of loop). Now I would like to add condition if button checked unblock, if not checked block.

I wrote following code:

<div >

  <input type="number" >
  <input type="text"   >
  <input type="email"  >
  <input type="checkbox" id="scale1" name="scales">
  <label for="scales">Scales</label>

</div>
function blockFileds() {

  let inputsForm = document.getElementsByClassName('block');
  let checker = document.getElementById('scale1');

  for (const singleField of inputsForm) {

    if (checker.checked) {

      singleField.disabled = false;
    } else {
      singleField.disabled = true;
    }
  }
}

blockFileds()

input are blocked, but I cant' unblock it.

CodePudding user response:

Remove the elements from the function, And attach addEventListener to the input

   
        let inputsForm = document.getElementsByClassName('block');
        let checker = document.getElementById('scale1');
        function blockFileds() {
            for (let singleField of inputsForm) {

                if (checker.checked) {
                    singleField.disabled = false;

                } else {
                    singleField.disabled = true;
                    
                }
            }
        }

        blockFileds()
        checker.addEventListener("click", (e)=>{
            blockFileds()
        })

CodePudding user response:

this way...

const 
  inputsForm = document.querySelectorAll('input.block')
, checker    = document.querySelector('#scale1')
  ;

blockFileds()
checker.onclick = blockFileds


function blockFileds()
  {
  inputsForm.forEach( singleField =>
    {
    singleField.disabled = !checker.checked
    })
  }
.block, label {
  display : block;
  margin  : .3em 0;
  }
<div >

  <input type="number" >
  <input type="text"   >
  <input type="email"  >
  <label>
    <input type="checkbox" id="scale1" name="scales">
    Scales
   </label>

</div>

CodePudding user response:

you can try this:

const inputsForm = document.getElementsByClassName("block");
const checker = document.getElementById("scale1");

function blockFileds() {
  for (let singleField of inputsForm) {
    if (!checker.checked) {
      singleField.disabled = "";
    } else {
      singleField.disabled = true;
    }
  }
}

checker.onclick = () => {
  blockFileds();
}
  • Related