wjmolina
wjmolina

Reputation: 2675

Passing ASP.NET Elements to JavaScript Functions

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?

Upvotes: 1

Views: 876

Answers (1)

emerson.marini
emerson.marini

Reputation: 9348

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?

Upvotes: 4

Related Questions