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
Sure, you could shorten your JS like this by setting one boolean to another.
I would write it as follows, since "checked" is a boolean:
The select menu will be activated when the checkbox is selected and will be inactive when the checkbox is not selected
The select menu will be inactivated when the checkbox is selected and will be active when the checkbox is not selected