skip to Main Content

I’m using JavaScript to code a function, that if checkbox is checked disabled the select dropdown, then if uncheck the checkbox and enable the select dropdown.

HTML:

 <input type="checkbox" id="flag">

  <select name="cars" id="select" disabled>
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
  </select>

This is how I do it:

 function summary()
  {
    if (document.getElementById('flag').checked) 
    {
      document.getElementById('select').disabled = true;
    }
    else{
    document.getElementById('select').disabled = false;
    }
  }

My question is, instead of repeating the duplicated code document.getElementById('select').disabled =, is there a shorter way to achieve this logic?

3

Answers


  1. Sure, you could shorten your JS like this by setting one boolean to another.

    function summary() {
      document.getElementById('select').disabled = document.getElementById('flag').checked;
    }
    Login or Signup to reply.
  2. I would write it as follows, since "checked" is a boolean:

    function summary() {
      document.getElementById('select').disabled = document.getElementById('flag').checked;
    }
    
    document.getElementById("flag").addEventListener("click",summary);
    <input type="checkbox" id="flag">
    
    <select name="cars" id="select" disabled>
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
    </select>
    Login or Signup to reply.
  3. The select menu will be activated when the checkbox is selected and will be inactive when the checkbox is not selected

    let flag = document.getElementById('flag');
    
    flag.addEventListener('click', () => {
        document.getElementById('select').disabled = !flag.checked;
    });
    <input type="checkbox" id="flag">
    
    <select name="cars" id="select" disabled="true">
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
    </select>

    The select menu will be inactivated when the checkbox is selected and will be active when the checkbox is not selected

    let flag = document.getElementById('flag');
    
    flag.addEventListener('click', () => {
        document.getElementById('select').disabled = flag.checked;
    });
    <input type="checkbox" id="flag">
    
    <select name="cars" id="select">
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
    </select>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search