I\'m hiding/showing a div based on the state of a checkbox.
You can directly set the .disabled
property on the element:
function toggle_form_element(name) {
var state = document.getElementsByName(name)[0].checked;
document.getElementById('sometimesHidden').disabled = state;
}
It's almost always better to modify the properties of an element rather than the attributes, and the semantics are clearer for boolean properties, too.
Note that while MDN suggests that this property is ignored on hidden fields:
disabled
This Boolean attribute indicates that the form control is not available for interaction. In particular, the click event will not be dispatched on disabled controls. Also, a disabled control's value isn't submitted with the form.
This attribute is ignored if the value of the type attribute is hidden.
testing in Chrome 27 shows that Chrome does honour the disabled
attribute and prevent submission of form values for hidden
fields.
Furthermore, the W3C spec makes no such distinction. It simply says that "Controls that are disabled
cannot be successful".