-1

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
AlexanderD
  • 596
  • 2
  • 10
  • 22

2 Answers2

0

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.

Liam
  • 27,717
  • 28
  • 128
  • 190
Gusman
  • 14,905
  • 2
  • 34
  • 50
  • I've forgot to say I'm using a Master Page, so the id ends up to be something like 'ctl00$ContentPlaceHolder1$TextBox' – AlexanderD May 03 '16 at 09:32
-1

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.

Undo
  • 25,519
  • 37
  • 106
  • 129
AlexanderD
  • 596
  • 2
  • 10
  • 22