I want to make html select tag only activated when a check box is checked,how can i??
+3
A:
Using Javascript:
<script type='text/javascript'>
if(document.getElementById("myCheckbox").checked) {
document.getElementById("mySelect").disabled = "";
}
else {
document.getElementById("mySelect").disabled = "disabled";
}
</script>
When this code is called, it checks if box is checked and disables select as appropriate.
Or, with PHP/HTML:
<form action='' method='post'>
<select <?PHP if($_POST['myCheckbox']==1) { echo "disabled='disabled'"; } ?> >
<option>blah</option>
</select>
<input type='checkbox' name='myCheckbox' value='1' />
</form>
When the form is submitted, this checks if box has been POST
ed and disables select as appropriate.
Steve
2010-10-20 01:12:23
Isn't the `disabled` property boolean?
Šime Vidas
2010-10-20 11:00:14
I thought that myself, but I've found it sometimes breaks with boolean values...unfortunately I forget the exact circumstances.
Steve
2010-10-21 00:05:45
Steve ,both the two codes don't work,and the select is enabled all the time
OdO
2010-10-21 13:28:16
+2
A:
function handler() {
var checkbox = document.getElementById("myCheckbox");
var select = document.getElementById("mySelect");
select.disabled = !checkbox.checked;
}
I tested the disabled property: It can be set to either true
/ false
or "disabled"
/ ""
. Both methods work in all browsers.
(I tested in Chrome, Firefox, Safari, Opera and IE9 beta)
Šime Vidas
2010-10-20 11:03:35
Is there a reason you don't use `select.disabled = !checkbox.checked` other than readability?
Dave Anderson
2010-10-20 11:18:00
@Dave I haven't thought of it. Good idea. However, I am not sure if setting boolean values to the disabled property is cross-browser safe.
Šime Vidas
2010-10-20 11:27:34