I've been finding quite a few people on the Client-Side forums on ASP.NET asking about how to bridge the gap between JavaScript and ASP.NET. The questions are usually related to getting data, or a variable, from JavaScript to ASP.NET and vice versa. So today I am going to show how to accomplish both tasks, along with some time saving tips. Ok, you know how I roll, let's get started.
Objective #1: Read and Set data to a TextBox Server Control from a JavaScript var
The only two things we'll need here is a TextBox Server Control and an Input button.
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<input id="Button1" type="submit" value="JavaScript" onclick="return myScript();"/>
Notice the onclick event of the input button. It's pointing to the myScript() JavaScript function that we have yet to create. Let's do it now.
function myScript()
{
// Reference to our TextBox1 Server Control
var txtBox = document.getElementById("<%=TextBox1.ClientID%>");
// Set
txtBox.value ="You ran myScript()";
// Read
var read = txtBox.value;
return false;
}
Pay very close attention to the "var txtBox" line. Look at the ID of the element. Now before we go on let me explain why I used <%=TextBox1.ClientID%> instead of the ID TextBox1. For .NET to keep track of all its server controls it generates IDs for each server control based on its heirarchy in the page. If you're looking at this page generated with a MasterPage you would get a different ID for the TextBox. Move the control into a Wizard and you'll get another ID.
Example: The same TextBox control inside a Wizard control looks like
<input name="Wizard1$TextBox1" type="text" id="Wizard1_TextBox1"/>
Notice the ID is now Wizard1_TextBox1. The JavaScript code would throw an error if it were looking for the ID TextBox1 because the .NET engine has rendered the control with a different ID. That's where ClientID comes in. ClientID contains the rendered ID of the server control. So no matter where you move TextBox1 on the page using TextBox1.ClientID will point to the correct element in HTML, and this is precisely what our JavaScript needs. This also saves you a lot of time should you ever want to move your controls around.
Side Note: The ClientID property should be used on Server Controls that implement the INamingContainer. This is to keep all control IDs unique (more here: http://msdn2.microsoft.com/en-us/library/3hc29e2a.aspx).
Continuing on now... Our txtBox variable now points to our TextBox1 server control. We can then set or read the value of the textbox using the next lines of code.
// Set
txtBox.value = "You ran myScript()";
// Read
var read = txtBox.value;
Finally we return false instructing the onclick event to stop any further processing. This stops the button from doing a postback. On the other hand you could return true. In this case the JavaScript code will run and then the form will postback.