How to disable TextBox on client-side click on CheckBox
Solution 1
<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>
Solution 2
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.
Solution 3
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'));
});
});
abatishchev
This is my GUID. There are many like it but this one is mine. My GUID is my best friend. It is my life. I must master it as I must master my life. Without me, my GUID is useless. Without my GUID I am useless.
Updated on June 04, 2022Comments
-
abatishchev almost 2 years
How to disable
asp:TextBox
onclient-side
click onHTML checkbox
or server-sideasp:CheckBox
usingJavaScript
?<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>