views:

400

answers:

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  A: 

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.

Jørn Schou-Rode
+1  A: 
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'));
    });
  });
Matt
A: 
<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>
abatishchev