help with dynamic creation of Javascript

I'm creating Javascript dynamically, using the ClientScriptManager.  In general, my Javascript works fine.   However, I want to use document.getElementById to get a reference to a control on my page.  This does not work.  I'm using alert to display the variable and it's always null.

Can anyone see an issue with the code below?  What might be wrong?

 Here's a relevant portion of my ASP code:

 <asp:TextBox runat="server" id="xyzreq_item" MaxLength="100" columns="60" cssclass="field_input" rows="2" textmode="MultiLine"></asp:TextBox>

Here's a relevant portion of my VB code-behind code:

Dim scriptText As New StringBuilder()
Dim cs As ClientScriptManager = thePage.ClientScript

scriptText.Append(" var x123 = document.getElementById('<%= xyzreq_item.ClientID %>'); ")

cs.RegisterClientScriptBlock(thePage.GetType, SCRIPTID, scriptText.ToString)
Who is Participating?

Improve company productivity with a Business Account.Sign Up

Lee SavidgeConnect With a Mentor Commented:
Just reference it directly. Should work as long as you want to put the value in the alert.

scriptText.Append(" var x123 = document.getElementById('xyzreq_item').value; ")

Open in new window

HLRosenbergerAuthor Commented:
That did not work either.  When the javascript runs, x123 is still NULL.   I don't get it.  

scriptText.Append(" var x123 = document.getElementById('xyzreq_item'); ")
Lee SavidgeCommented:
Try using RegisterClientScript instead of RegisterClientScriptBlock
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

HLRosenbergerAuthor Commented:
Ah, if I add this to the asp:   ClientIDMode="Static"

<asp:TextBox runat="server" id="xyzreq_item" MaxLength="100" columns="60" cssclass="field_input" rows="2" ClientIDMode="Static" textmode="MultiLine"></asp:TextBox>

Then your way works.  Does ClientIDMode="Static" tell the browser or ASP to not make any changes to the ID?

What's the difference between this syntax:

var x123 = document.getElementById('<%= xyzreq_item.ClientID %>');

and this:

var x123 = document.getElementById('xyzreq_item');
Lee SavidgeCommented:
If memory serves me the default ClientID mode is Predictable. Setting it as static essentially tells the page not to change the control names from what you specify. By default the control names, I think, also include the container name. I'm a bit vague on it I'm afraid.
HLRosenbergerAuthor Commented:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.