简体   繁体   中英

Dynamically adding class to readonly field in ASP.NET

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.

You explicitly set the input's ID as "TextBox" but you're trying to retrieve it as <%= TextBox.ClientID %> , use "TextBox" as the ID (and better, give a more meaningful name to the ID).

ClientId is used for ASP .net controls which have it's ID autogenerated by the ASP runtime.

Turns out I was referencing the wrong control. Referencing the correct control in the script 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM