jorame
jorame

Reputation: 2207

Enable/Disable an asp:TextBox Control based on CheckBox.Checked true or false

I need to enable/disable an asp.TextBox/Input depending on a CheckBox. If the CheckBox.Checked = true then I need to enable the asp.TextBox/Input or if the CheckBox.Checked = false I then need need to disable the asp.TextBox/Input.

Below is the code I have but it only works on first click, meaning if I check the box it will enable the asp.TextBox/Input but if I uncheck it will not disable the asp.TextBox/Input.

Also, by default the asp.TextBox/Input is disable on Page_Load.

//If checked it should enable the input.
//If unchecked it should disable the input.
If Port is Required?<label class="checkbox">
                        <input type="checkbox" id="isportreqinput" name="isportreqinput" runat="server" onclick="fncport(this.form.isportreqinput, this.form.porttxt);"  />
                        <span class="metro-checkbox">Check Me</span>
                    </label>

//This is the input I need to disable/enable depending on the checkbox
<input type="text" name="porttxt" id="porttxt" runat="server" disabled="disabled" />

    <script type="text/javascript">
        function fncport(control, objname) {

            if (control.checked == true) {
                objname.disabled = false;
            }
            if (control.cheched == false) {
                objname.disabled = true
            }
        }
    </script>

Upvotes: 0

Views: 4994

Answers (2)

jiiri
jiiri

Reputation: 330

Not sure if you pasted your code or copied it. But there are a few syntax issues:

 if (control.cheched == false) {
            objname.disabled = true
 }

Should be:

 if (control.checked == false) {
            objname.disabled = true;
 }

Upvotes: 0

scott.korin
scott.korin

Reputation: 2597

this.form.isportreqinput is not a valid way to get a reference to the isportreqinput checkbox from within your HTML. this is actually a reference to the checkbox.

If you need to pass in the ids of the checkbox and input to your function, pass them in as text and use document.getElementById()

<label class="checkbox">
    <input type="checkbox" id="isportreqinput" name="isportreqinput" runat="server"    
        onclick="fncport('isportreqinput', 'porttxt');"  />
    <span class="metro-checkbox">Check Me</span>
</label>

<input type="text" name="porttxt" id="porttxt" runat="server" disabled="disabled" />

Also, you mispelled checked in the second if statement. You don't even need either if statement, just set the disabled value to the opposite of the checked value.

    function fncport(controlid, objnameid) {
        var control = document.getElementById(controlid);
        var objname = document.getElementById(objnameid);

        objname.disabled = !control.checked;
    }

Upvotes: 1

Related Questions