Toggle (Enable and Disable) a Form Field With a Checkbox: JavaScript 101

At some point I needed a form field disabled by a checkbox. Here's how I did it.


Today at work I was creating a form.

I’m not a big JavaScript buff, but one of my tasks was to use a checkbox to toggle a form field between “enabled” and “disabled”. So, after browsing the web for a solution, I decided it would be simpler to roll up my sleeves and get dirty writing my own function.

Here is what I came up with:

JavaScript toggle() Function:

function toggle(checkboxID, toggleID) {
     var checkbox = document.getElementById(checkboxID);
     var toggle = document.getElementById(toggleID);
     updateToggle = checkbox.checked ? toggle.disabled=true : toggle.disabled=false;
}

HTML Input Fields:

<input
    id="example"
    name="example"
    onClick="toggle('example', 'disableMe')"
    type="checkbox" value="1" /> When this is checked, something is disabled <br />

<input
    id="disableMe"
    name="disableMe"
    type="text"
    value="This input box will get disabled" />

This is pretty basic.

What we are doing is feeding the function the ID of the checkbox field, and the ID of the form field we want to disable. When you check or uncheck the box, we call the toggle() function, which determines what action we took - if it is checked, we disable the form field, and if it is unchecked, we enable the form field.

If you want to accomplish the opposite (checked = enabled, unchecked = disabled), simply switch the disabled values in the function:

function toggle(checkboxID, toggleID) {
  var checkbox = document.getElementById(checkboxID);
  var toggle = document.getElementById(toggleID);
  updateToggle = checkbox.checked ? toggle.disabled=false : toggle.disabled=true;
}

I haven’t done extensive testing as to whether this works across all browsers, but it seems to be working just fine in Firefox and Chrome.

Here’s a demo:

When this is checked, something is disabled