views:

46

answers:

2

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 POSTed and disables select as appropriate.

Steve
Isn't the `disabled` property boolean?
Šime Vidas
I thought that myself, but I've found it sometimes breaks with boolean values...unfortunately I forget the exact circumstances.
Steve
Steve ,both the two codes don't work,and the select is enabled all the time
OdO
+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
Is there a reason you don't use `select.disabled = !checkbox.checked` other than readability?
Dave Anderson
@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