How to get TextBox value that was set by JavaScript

Hi, I used a JavaScript to set a TextBox value.  This works ok, it displays the correct value when the page is rendered.  But when I try to access the TextBox value using the server side code, it does not read the new value.  (I'm assuming it is because the JavaScript code is not actually adding the Text property to the rendered HTML)


Here is my test code, does anyone have any ideas?


protected override void OnLoad(EventArgs e)

			TextBox tb = new TextBox();
			tb.ID = "TestTextBox";
			tb.Visible = true;
			tb.Text = "dsfsdfsdf";
			this.Form.Controls.AddAt(0, tb);

			string JavaScript = "&lt;script type=\"text/javascript\"&gt;document.getElementById('ctl00_TestTextBox').value = top.location.href;</script>";
			ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "TopLocation", JavaScript, false);

			using (TextBox tb2 = (TextBox)this.Form.FindControl("TestTextBox"))
				if(tb2 != null)
					Response.Write("test: " + tb2.Text);


My goal here is to access the top.location.href value server side.

12/12/2007 5:00:46 AM 24353 articles. 1 followers. Follow

5 Replies

Similar Articles

[PageSpeed] 53


you cannot get the values assigned to textbox by Js in Server side... you need store the value in hidden field at client side and reassign the same value from hidden to textbox at server side.


Software Engineer.
12/12/2007 6:07:55 AM


As Vasanthakumar said, assign the values in hidden field and access it in code behind 

Software Engineer
12/12/2007 6:13:04 AM

I think the problem is because the dynamically created textbox hasn't been rendered to client yet, before the postback.

Do you get any js errors? Are you sure it finds the textbox? 

- Can you use a non dynamic textbox in your case? 

(- or make your javascript bigger, and let the js make the textbox with document.createElement..!? )

Validation Complete
========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==========
I'll always mark your post(s) as answer when it is!
12/12/2007 2:11:19 PM

You are trying to read the value on the Page  Load? You need to learn how a web application works. The JavaScript is not run until the entire page is sent down to the client and rendered. The server can not interact with the clientside value because of this. You need to post the form back up to the clietn to read any information added by JavaScript.

Eric | Twitter epascarello | LinkedIn
12/12/2007 2:22:39 PM

Thanks  mr_breaker ,vasanth.kumar.d ,A1ien51  for your post. I trapped in similar situation and solve it by using hidden field. Although before read your posts i solved it using hidden field. By reading your posts i knew the reason behind this. Thanks A1ien51   again about Page lifecycle Idea.

Thanks to all you .



with regards

I never lose, some people are just better than me at winning.
5/1/2008 8:13:44 AM

Similar Artilces:

Get values set by javascript to .net enabled textbox
I have a bit of javasript that writes a value to a text box.  The text box is read only. Textbox code:<input type="text" id="txtColor1" runat="server" readonly="readonly" size="6" /> Snippet from javascript functioncolorBox = document.getElementById('<%= txtColor1.ClientID %>');colorBox.value = colorCode;  Code behind:string color1 = txtColor1.Value Whenever I attempt to get the value out of the text box after it has been changed by the javascript, it always reverts back to the old data and not the new. Anyo...

textbox value set on client side, is not visible on server side or, on the source of the page.
hi, I have a textbox on my webform. the first time I load my page I fill this textbox with  "name" on the server side. once the page is loaded I set the value of the textbox to "thisIsme" with client side code. I even see a different text in the texbox. client side:document.all('txtnameInput').value =  'thisIsme'; server side:Me.txtnaam.Text 'is stil "name" and not "thisIsme" Why is this happening? on the webpage I see the text "thisIsme", but when I look at the source of the webpage I still see the old value in it. it's very odd... I am NOT setting the value back to "name" on the page load event of the postback. any idea's why this is happening ?see my blog at and check the future of open mobile widget solutions at When you look at the "source code" of a web page, you see the HTML which was originally sent from the server, if you change any value inside any element on client side (textboxes, selects, checkboxes...) you won't see it on the "source code", but the "page" object into the browser does keep them well. Now if you don't get the rigth value ("thisIsme") when you submit the form back to the server that could be a different issue....

Get textbox value in client side
My problem is that in my ascx file i have a textbox & a input buttom with a javascript function that will validate the textbox: .... <script lang="javascript"> function Test() { if (document.all.txt1.value == "") { alert(); return; } } </script> .... <asp:textbox id="txt1" runat="Server"></textbox> <input type=button id="cmd1" onclick="javascript:Test();" value="Add"> .... But the function don't work, because the textbox control isn't...

How can I set client side values as server side values?
Hi, Can anyone tell me how I can get client side values such as document.referrer, navigator.appName etc... into server side scripts? There are some client side values I'd like to set as session vars and insert into the db? How do I go about this? Thanks for any pointers Davlon PS (I'm using powersite Pass them as page parameters, e.g., http://myserver/myurl?document.referrer=whatever&navigator.appName=yadayada Then, in your server-side script, just loop through the document.value array and get these values. -- pbm_hopethishelps, Roy Kie...

Getting Textbox Watermark Text in client side javascript
Can somebody tell me how I can go about grabbing the Text value of a TextBoxWatermark control from client side javascript?  I need to make a comparison/validation if a text box has been filled out (non-blank) and of course the watermark fills in the text value of the text box when grabbing the property (of the text box) per javascript? So, I need to somehow grab the text from the watermark in javascript and then compare to the text box contents to see if the text in the textbox is the water mark text or not.  Any information would be greatly appreciated.  Thanks!  Th...

Get label value on server side set by javascript
 HelloHow are all here.I have set the label text using javascriptdocument.getElementById("lblEmail").innerHTML = Login;Now when I try to get value (i.e. Text), by lblEmail.Text on ASP.Net server page, then the label shows no value or text. i.e. it is empty. why this is happening? how can I get value on Form set by Javascript?regards change in coding document.getElementById("lblEmail").value= "Hello World";   Please remember to click "Mark as Answer" on the post that helps you. This can be beneficial to other community members reading the thread. Hi,The label control is a read-only control... you can't overwrite it from client side and maintain its value if a postback is executed.To solve this issue... besides to write in the label, you can write the same value in a HiddenField control... and retrieve the value of the HiddenField from the server:document.getElementById("lblEmail").innerHTML = Login;document.getElementById("hiddenField1").value = Login; Any doubt, post your comment.Segundo Serrano P.Ing. Sistemas Try this: document.getElementById(<%# lblEmail.ClientID %>).innerHTML = Login;  As mentioned, you cannot specify value to the Label control using Javascript. Use a hidden variable... <input type="hidden" name="hidVal" id="hidVal" runat="server" />  And use...

Getting Value from Client-side InputBox to .net variable
hi, im doing a login page for our timekeeping. Since there's no msgbox available on, im doing it dynamically via javascript. How do i Get the value frm a dynamically written javascript (such as inputbox) to a .net variable? here's the logic of my program, user logs in hits the button and sub-routine Login will be fired, if user is late -- call Check_Late Sub, this is whre the client-side script was built -- then after that i wanted to be able to get the value from an inputbox. '// if button login clicked Sub Login(Sender As Object, E As EventArgs) .......

Get the Dropdownlist text and value using Javascript from client side
Hi, I am encountering a problem about how to get the Dropdownlist text and value using Javascript from client side. I am using C# in Visual Studio 2005 and Javasript . The example codes are like: ( In this example code, I would like to access the text and value of the DropDownListReports in the run() function of Javascript. How can I do that? Any ideas? Thanks a lot. ) protected void Page_Load(object sender, EventArgs e) {              if (!Page.IsPostBack)               {                     DropDownListReports.Items.Clear();                     ListItem listItem = new ListItem();                     listItem.Text = "aText";                     listItem.Value = "aValue;                     DropDownListReports.Items.Add(listItem);               } }   on the its source page:   <asp:Drop...

The value set to controls at client side donot persist for each page load, else it is again set to the default value...??
 I am trying to set date to the textbox field using javascript (Client side), the function is as follows. function From_calendarPicker(){                                var    sDPath = "../Calender.aspx";                 var    oWin = window.showModalDialog(sDPath, null, "dialogWidth:300px;dialogHeight:250px;help:0;status:0;scroll:0;center:1");  &nbs...

Hidden Field that is set on server side...not getting the last updated value from client?
Hi, I have a hidden field that tracks errors in my server side 2.0 code.  However, when I set the value to an error (from it's default value "NotSet") in the server side code and then when trying to access that Hidden Variable from the client the value is still set to the default value, "NotSet" instead of the error information. Any ideas as to what is going on here? Thanks in advance!   Server Side....  catch (Exception er) { Errors.Value = er.Message; o o o } Client Side.... function getErrors() { var cho = document.getElementById('<%=Errors.ClientID...

how to get value from client side script Prompt window to a session var in .net
hi guyz, i hav a problem with getting a value from a client-side inputbox to a session var in .net. is this possible? however, when i click submit button this is the code that's triggered. dim sb as New System.Text.StringBuilder sb.append("<script language=" & """" & "vbscript" & """" & ">") sb.append(vbcrlf) sb.append(vbcrlf) sb.append("do while xLate =" & """" & """") sb.append(vbcrlf) '//prompt window, val...

How to get the value from a textbox of a datagrid template column while in edit mode using client javascript
Hi, I have added a template column to my datagrid, and in EditItemTemplate tags i am displaying an asp textbox <EditItemTemplate> <asp:TEXTBOX id=TextBox1 Text='<%# Container.DataItem("MyDataField) %>' Runat="server"></asp:TEXTBOX> </EditItemTemplate> i need to get the value of the textbox using a client side scripting language like Javascript. i tried the document.forms[0].TextBox1.value option but does not work I need a solution for this Waiting for replies. i'm trying to figure out the same thing, my current m...

How to get the Client side values in server side code.
Hi all, i have a proble i need to get the client side javascript values in C# code at server side. how can i pass those values? i am using version 1.1, i kno thatwe can use callback events mechnisam in 2.0 or ajax ,apart from that how we can pass? My problem is i need to stop the execution of the code based on after reciving values from the client   any ideas please???   Million thanks RamCheersRam MCP Hello Ram, a common approach is from javascript set an hidden field, then issue a postback. On the server-side, handle the post-back. Feel free to go deeper in your que...

Getting value from a textbox control that was filled with a value from javascript
 I have a textbox control (seen below txtMileageDollars1) that gets filled with javascript based on the number of miles a user types into another textbox (txtMileageMiles1) control.  When I post back with the submit button, the value is blank.  I've tried setting EnableViewState to false, but still cannot get a value on postback.  Does anyone have a solution?   Miles<asp:TextBox ID="txtMileageMiles1" runat="server" Width="50px"></asp:TextBox>   Total (txtMileageMiles1 * rate with javascript)<asp:TextBox...

repeater with textboxes. how to read the textbox values on client side
Hi  I have a data bounded repeater with text boxes attached. How can I read the values of the textboxes using javascript?? Could not find a proper link.. Appreciate any solution , thanks     The repeater will add a prefix to each textboxes ID to ensure uniqueness.  The following function will loop through all textboxes of the repeater, and if the ID of the given textbox contains the string specified, the it will consider it a match and you can access it's value property easily.  Here is the function: function textboxFinder() { var repeater = document.getElementById('Repeater1'); var inputs = repeater.getElementsByTagName('input') var txtId = 'txtName' //ID of textbox in repeater template for(var i = 0; i < inputs.length; i++) { if(inputs[i].type == 'text') { if(inputs[i].id.indexOf(txtId) != -1) { //Matching textbox, lets show its value alert(inputs[i].value); } } } }   I am sure you will have to modify this a little bit to perfectly suit your needs, but this should give you a great place to start. This function has a slight flaw.  If you have similiarly named textboxes in your repeater (like txtName and txtNameOfDog, for example), and you use this function to search for all "txtName" textboxes, it will consider the txtNameOfDog textboxes as a ma...

pass client textbox value to a server side textbox
HiDoes anyone know how in javascript to pass a client side textbox value to a server side textbox?Thanks in advance.Graham. An asp textbox is a resular textbox. so you do it the same way.document.formName.elementName.value = document.formName.elementName2.value;One thing to note is that the asp textbox is going to have a slightly different name then what you named | Twitter epascarello | LinkedIn...

Javascript set textbox equal to another wizardstep textbox value
 I am trying to set the textbox in the "billing section" of my wizard. Say WizardStep4. I am trying to set it to Another textbox's value in WizardStep3.The example: If a users checks "Use my shipping address as my billing address", all of the information from the shipping section should copy over to the billing section. It's not working. I'm getting an Object Required.Here's the function called by the checkbox check on the billing page WizardStep4....         function FillBillingAddresswithShippingAddress()...

Getting hidden variable value from server side in client side
hi,        I am struck in problem. I have a hidden field in my form and i am setting some value in that.         Now i wnt to use this value from client side but i m not able to retrieve it. All i am getting there is an object.         I feel the hidden field is not able to hold that value.         <input type="hidden" id="hdnVar" runat="server" />         in code behind      ...

How to Encrypt the value of textbox in client side and Decrypt it in server side?
How to Encrypt the value of textbox in client side and Decrypt it in server side? THere is no use in decrypting ur content @ client side since a normal user can view the decrytion logic when he takes 'view source' option 'SSL' technology is used in this situations. SreejithSreejith Sreejith: he did not ask to decrypt it on client-side! Take a loot at this article on the Cryptography application block: Stodola ← Come check out my blog! Another good article:

Problem accessing server side array values from javascript client side function
i faced the following problem ..i have an array that store the values of a resultset row under the server side coding.How do i retrieve them under my client side javascript function.I wrote the following coding under my client side function and it got an error.BSCStr is an array storing data from a resultset row which i did under the server side coding. From client side function: addr=addr + "&C" + i + "=" + <%=BSCStr[i]%>; First of all, you can't mix server-side and client-side code. The reason is that the protocol that is used to communicate betwee...

Problem accessing server side array values from client side javascript function
i faced the following problem ..i have an array that store the values of a resultset row under the server side coding.How do i retrieve them under my client side javascript function.I wrote the following coding under my client side function and it got an error.BSCStr is an array storing data from a resultset row which i did under the server side coding. From client side function: addr=addr + "&C" + i + "=" + <%=BSCStr[i]%>;...

how do i get selectedValue of drop down list server side if i am populating it using client side javascript?
 Hi All.I am populating a drop down list client side using: The drop down list is populated based on a selection of another drop down list. ddlList.options[i] = new Option(1,2); as an exampleThe populating is done as i need it to. However, a button click event i am trying to get the selectedValue of the ddlList. However, it doesn't give me it. It only gives me the selectedValue of the drop down list on first rendering. Any ideas on how i can get it?   Could You paste some code? That would be helpful. Thanks S@ss (Shashi Shekhar Singh)My BlogPlease mark a post as ANSWER ...

How to get value from client side
in my program I want to send a value to my modal popup, how can I do that? Thanks lyha Is it what you are looking for? Anish DevasiaMCP,MCAD---------------------------------------------------...

Client Side Get Value
I am trying to retrieve the current value of a textbox from my code behind and assign it to a variable. Currently I am using something like   dim id as new string  id = txtbox1.text.toString()  When I am loading the page I am checking for a cookie then putting the value of the cookie in the txtbox1. Currently when I use the code above it gets the value that was put in there by the cookie. Is there a way to retrieve the value if the user changes what the value is of that textbox? I know in Javascript there is  txtbox1.value But I am having trouble taking the value ...

Web resources about - How to get TextBox value that was set by JavaScript -

JavaScript Kit- Your comprehensive JavaScript, DHTML, CSS, and Ajax stop
Your comprehensive JavaScript, DHTML, CSS, and Ajax stop

Let's Code: Test-Driven Javascript by James Shore — Kickstarter
James Shore is raising funds for Let's Code: Test-Driven Javascript on Kickstarter! A screencast series focusing on rigorous, professional Javascript ...

Eloquent JavaScript: A Modern Introduction to Programming
... and pragmatics. I loved the tutorial-style game-like program development. This book rekindled my earliest joys of programming. Plus, JavaScript! ...

Lightbox (JavaScript) - Wikipedia, the free encyclopedia
On a Lightbox-enabled page, a user can click an image to have it magnified in a Lightbox window, which resizes itself according to the size of ...

Open Directory - Computers: Programming: Languages: JavaScript: Tools: Obfuscators
about dmoz - help Top : Computers : Programming : Languages : JavaScript : Tools : Obfuscators Tools for obfuscation/compression JavaScript code. ...

Facebook Open-Sources JavaScript Static-Type Checker Flow
The latest software to be open-sourced by Facebook is Flow , a static-type checker for JavaScript . (more…) New Career Opportunities Daily: ...

Under the Hood: The JavaScript SDK - The use of polyfills - Facebook
Facebook Engineering hat eine Notiz mit dem Titel Under the Hood: The JavaScript SDK - The use of polyfills geschrieben. Du kannst den vollständigen ...

Quickstart: Facebook SDK for JavaScript
This quickstart will show you how to setup the SDK, load social plugins, trigger a dialog, and get it to make some basic Graph API calls.

Facebook App Devs Get Javascript
It has been an oft-lamented fact of the Facebook Platform thus far in its life that, in order to use all but the most simple of Javascript functionality–the ...

Badass JavaScript (@badass_js) on Twitter
WebGLWorker is an open source library that allows using WebGL from Web Workers. Great work as always from @kripken .… ...

Resources last updated: 2/27/2016 11:05:17 AM