1

i am creating a dynamic textbox control from the code behind... my question is. how can i attach the javascript code to a dynamic created textbox?

here is the code that creates dynamic Textbox.

TextBox t = new TextBox();
t.ID = "txtDynamic";
t.TextMode = TextBoxMode.MultiLine;
t.Rows = 7;

below is the Javascript....would like to add to the above control created.

$('txtDynamic').limit('140','#charsLeft');

2 Answers 2

1

When using ASP.NET WebForms I always try and stay away from referring to IDs in my javascript because the rendered ID may not always be the same as the server side ID.

Use CssClass to ensure consistency, and a . prefix instead of # prefix in your jquery selector.

TextBox t = new TextBox();
t.ID = "txtDynamic";
t.TextMode = TextBoxMode.MultiLine;
t.Rows = 7;
t.CssClass = "limit140";

$('.limit140').limit('140','#charsLeft');
Sign up to request clarification or add additional context in comments.

Comments

1

Ids get changed by the serverside code so you need to use the clientid. Also in your example, you are missing the # for the jQuery selector.

$('#<%=txtDynamic.ClientID%>').limit('140','#charsLeft');

This will only work if the code is inline JavaScript, it will not work in an external file.

If not it is better to set a CSSClass and reference that in the selector.

Comments

Your Answer

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