We help IT Professionals succeed at work.

Javascript in ASP.Net page

Camillia asked
I'm following this example (the first part) and it works fine in a page with a form.

I want to do the same in a content page (page that has a master page). But i keep getting
"txtMessage is not defined."

I think this is because of "is.form.remLen" but I'm not sure. What can I do? thanks
Watch Question

I'd guess that you didnt do the stuff listed in the section: "Adding some Server Side smarts".

When you add your page to a masterpage then your textbox id is going to rendered using the "inamingcontainer" convention. So when the id changes it is breaking the code.

But there's some bigger issues, and you can likely ignore the above for a simpler fix.

Also lets take a look at this:
<asp:TextBox ID="txtMessage" TextMode="MultiLine"  Width="200px" Rows="3" runat="server"  onkeyup="textCounter(txtMessage, this.form.remLen, 160);" onkeydown="textCounter(txtMessage, this.form.remLen, 160);" />

Specifically this:
onkeyup="textCounter(txtMessage, this.form.remLen, 160);"

If I remember correctly this works because of a quirk in IE where you can pass "txtMessage" as a parameter for your function (because it sees it as an object for some reason) and it works as though you were passing (this). I'm pretty sure if you try this in FF it will fail. I'm also 99% sure if used with a masterpage this will fail.

Never-the-less that is just old memory that may be tricking me. I'm pretty sure I stumbled on this once and thought it was cool, then realized it only worked in IE and so stopped using it.

What may be better all around and resolve both your "masterpage/clientID" issue and the "browser specific" issue is changing to this:

<asp:TextBox ID="txtMessage" TextMode="MultiLine"  Width="200px" Rows="3" runat="server"  onkeyup="textCounter(this, this.form.remLen, 160);" onkeydown="textCounter(this, this.form.remLen, 160);" />

Now the parameter "field" in function textCounter(field, countfield, maxlimit) should know the textbox without needing a clientID or any ID at all.

Its worth noting that when I tested this on a masterpage/page setup I had the darndest time getting the onkeydown to see my javascript function unless I moved the script to the end of the page under the textboxes? Not sure what that was about...(likely something to do with calling form.elements as parameters).

Hope that helps.
wow, thanks for the detailed answer. Let me read. You said you tested it, can u attach your test pages here?

sure its nothing fancy just your code... see attached