JavaScript check and uncheck checkbox, after uncheck checkbox return to the original state

Advertisements

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?

>Solution :

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

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

Leave a ReplyCancel reply