3

How to disable asp:TextBox on client-side click on HTML checkbox or server-side asp:CheckBox using JavaScript?

<script type="text/javascript" language="javascript">
    function enableTextbox() {
        // ?
    }
</script>

<table>
    <tr>
        <td>
            <input id="checkTake" onclick="enableTextbox" title="Take?" />
        </td>
    </tr>
    <tr>
        <td>
            <asp:TextBox runat="server" ID="txtCommission" />
        </td>
    </tr>
</table>

3 Answers 3

4

The tricky part here is that ASP.NET assigns autogenerated id attributes for all runat="server" elements, inlcluding your TextBox. A simple solution is to "inject" the generated id into the script:

function enableTextbox() {
   var txtCommision = document.getElementById("<%= txtCommision.ClientID %>");
   txtCommision.disabled = !this.checked;
}

If you prefer to do it without this type of "spaghetti code" - maybe you want your JavaScript in a seperate file - you can avoid using the id for selecting the <input> field. Instead you can decorate it with a class. In that case, you might want to use some kind of selector library to find the control in JavaScript, jQuery being a popular option.

Sign up to request clarification or add additional context in comments.

Comments

2
<script type="text/javascript" language="javascript">
    function enableTextbox(checkbox) {
        document.getElementById('<%= txtCommission.ClientID %>').disabled = !document.getElementById(checkbox).checked;
    }
</script>

<table>
    <tr>
        <asp:CheckBox runat="server" ID="checkTake" onclick="enableTextbox(this.id)" Checked="true" Text="Take?" />
    </tr>
    <tr>
        <td>
            <asp:TextBox runat="server" ID="txtCommission" MaxLength="8" CssClass="right" />
        </td>
    </tr>
</table>

Comments

1
function enableTextbox() {
  document.getElementById("<%= txtCommision.ClientID %>").disabled = !document.getElementById("checkTake").checked;
};

You need to actually invoke enableTextbox as well:

<input id="checkTake" onclick="enableTextbox()" title="Take?" />

jQuery:

  $(document).ready(function () {
    $('#checkTake').bind('click', function () {
      $('#<%= txtCommission.ClientId %>').attr('disabled', !$(this).attr('checked'));
    });
  });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.