HTML
<input id="TextBox" type="text" runat="server" readonly="readonly" />
JS
function MyFunct(sender, args) {
var TextBox = document.getElementById('<%= TextBox.ClientID %>');
if (true) {
TextBox.value = "somevalue";
TextBox.setAttribute('readonly', 'readonly');
$('#<%= TextBox.ClientID %>').addClass("disabledTb");
}
else {
TextBox.value = "";
TextBox.readOnly = false;
$('#<%= TextBox.ClientID %>').removeClass("disabledTb");
}
}
CSS
.disabledTb {
background-color: rgb(235, 235, 228);
color: rgb(84, 84, 84);
}
The readonly propery is working, I had to change the input from an asp:TextBox to a standard HTML textobx because otherwise the value wouldn't be retrieved to server side and I didn't want to use a hidden field.
However, now the .disabledTb class is not applied anymore. the rest of the code works fine, and changing
var TextBox = document.getElementById('<%= TextBox.ClientID %>');
to
var TextBox = document.getElementById('#<%= TextBox.ClientID %>');
causes a null reference seen in the console
Update
I forgot to say I'm using a Master Page, so the id ends up to be something like 'ctl00$ContentPlaceHolder1$TextBox'
SOLUTION
Turns out I was referencing the wrong control. Fixing that solved my problem. The rest of the code is totally usable.
referencing a control with # in the call to the ID is required for jQuery functions but not plain Javascript. <%= TextBox.ClientID %>
will work even for HTML inputs where the runat attribute is set to server. This will provide the correct ID when using master pages.