Is there any way to enable a form element(s) based on the selection in a <select> drop-down? I’m trying to enable/disable a group of checkboxes depending on which option is chosen in the <select> above it.
I know how to enable/disable something when a box is checked (or text is entered into it) but I have no clue how to handle the <select> option.
Here’s a simple form:
<form id="userInfo">
<p><label>Gender?
<select name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</label></p>
<p><label>Pregnant? <input type="checkbox" name="pregnant"></label></p>
</form>
Put your script at the bottom:
<html>
<head>
</head>
<body>
...
<script src="script.js"></script>
</body>
</script>
Attach an onchange event to the select box:
var form = document.getElementById('userInfo'),
gender = form.elements.gender;
gender.onchange = function () {
...
};
Disable the checkbox depending on the index of the selected option:
gender.onchange = function () {
var form = this.form;
if (this.selectedIndex === 0) {
form.elements.pregnant.disabled = true;
} else {
form.elements.pregnant.disabled = false;
}
};
and finally, trigger the onchange event so that the checkbox updates when the page loads.
gender.onchange();
Works awesome! Although the action is reversed, but that’s easy to change.
Now I just have to get it to work on multiple checkboxes (change from the customer) but I think I can make out how to do that.
Thanks Paul!