Setting server-side textbox with javascript?

G

Guest

In the Page_Load() of my webForm, I have the following code, and on my HTML
button, the onclick button calls writeVal() (the javascript function). When
I click on the button, I see the messagebox from the Alert(), but the
server-side Textbox text is not set to 'TEST'. I get a javascript error
saying, "document.getElementById(...) is null or is not an object.". What
could the problem be? The textbox is inside a Wizard control. Here's the code:

protected void Page_Load(object sender, EventArgs e)
{
string scr2 = @"<script>
function writeVal()
{
alert('test');
document.getElementById('txt_name').innerText = 'TEST';
}
</script>";
Page.RegisterClientScriptBlock("writeVal", scr2);
}

I can only assume that the Textbox being inside the Wizard could be causing
the error. I'm using VS2005 v2.0

Thanks.
 
M

Mark Rae

In the Page_Load() of my webForm, I have the following code, and on my
HTML
button, the onclick button calls writeVal() (the javascript function).
When
I click on the button, I see the messagebox from the Alert(), but the
server-side Textbox text is not set to 'TEST'. I get a javascript error
saying, "document.getElementById(...) is null or is not an object.".
What could the problem be? The textbox is inside a Wizard control.

The "problem" is exactly as you describe it - the textbox is inside a Wizard
control, which means that by the time the HTML comes to be rendered to the
browser, the client-side name of the textbox is no longer just txt_name -
it's probably something like the name of your Wizard control plus an
underscore plus "txt_name". Do a View Source and you'll see what I mean.

txt_name.ClientID will tell you the name of the textbox client-side i.e. the
name that the client-side JavaScript will need to reference.
 
M

Mark Fitzpatrick

If it's an ASP.Net textbox, keep in mind that the ID that will be given to
it when rendered is not the same ID that you set as it's name. A unique name
will be generated for it by the framework. You should be able to reference
it from the ClientId property such as:

document.getElementById('" & txt_name.ClientID & "').innerText = 'TEST';

This should inject the clientid of the text box inside the string. This is
identical to the UniqueID name generated for the control, except the
clientid uses underscores instead of the UniqueID's colons, which can't be
read in javascript.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,900
Latest member
Nell636132

Latest Threads

Top