1

I have created the following text-box and label:

<asp:TextBox ID="MyTextBox" runat="server"/>
<asp:Label   ID="MyLabel"   runat="server"/>

Moreover, I have created the following JavaScript function:

function characterLimit(myTextBox, myLabel)
{
    myLabel.innerHTML = myTextBox.value.length + '/' + myTextBox.maxLength;
}

Finally, in the code-behind, I have performed the following:

TextBox1.Attributes.Add("OnKeyUp", "characterLimit(MyTextBox, MyLabel);");

characterLimit() gets called. However, nothing happens; it is as though I am passing MyTextBox and MyLabel incorrectly (above). What is the correct way of doing this?

1 Answer 1

4

Use the ClientID property. This will help in the case you start using MasterPages, which changes the controls IDs.

But, in this specific case, I guess it's just about sticking quotes around the IDs when sending as parameters.

TextBox1.Attributes.Add("OnKeyUp", "characterLimit('" + MyTextBox.ClientID + "','" +  MyLabel.ClientID + "');");

Following a suggestion in the comments, you should also slightly change your Javascript code:

function characterLimit(myTextBox, myLabel)
{
    document.getElementById(myLabel).innerHTML = myTextBox.value.length + '/' + document.getElementById(myTextBox).maxLength;
}

And, just as a tip, have you tried jQuery yet?

Sign up to request clarification or add additional context in comments.

5 Comments

Those IDs need to be wrapped in document.getElementById() to work with the characterLimit() method as presented. TextBox1.Attributes.Add("OnKeyUp", "characterLimit(document.getElementById('" + MyTextBox.ClientID + "'),document.getElementById('" + MyLabel.ClientID + "'));");
The OP can do this in the Javascript function to keep the code clean.
Agreed that would be the better place for it.
I ended up using jQuery. Thank you for the suggestion. :-)
Com certeza vai diminuir seu trabalho codificando Javascript. :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.