views:

60

answers:

2

Hi,

I have an asp.net web form with a couple of asp.net textbox controls:

<asp:TextBox ID="txtTextBox" runat="server" /> .

I have a javascript file tools.js that are included in the page:

<script src="tools.js" type="text/javascript"></script>

How can I access the value from txtTextBox from javascript?

Ive tried using

document.getElementById('<%= txtTextBox.ClienID %>').value;
document.getElementById('<%= txtTextBox.UniqueID %>').value;
document.getElementById('<%= txtTextBox %>').value;

but none of them works.

Any ideas?

+3  A: 

You're missing a t on the ClientID (correct!) solution :), like this:

document.getElementById('<%= txtTextBox.ClientID %>').value;

Note though the above code has to be in the page so it prints out like this to the client:

document.getElementById('txtTextBox').value;
//or if it's deeper:
document.getElementById('Parent_txtTextBox').value;

If it's in an external js, then it prints out literally like this, without replacing the <%= %> part:

document.getElementById('<%= txtTextBox.ClientID %>').value;

Since there's no <input id="<%= txtTextBox.ClientID %>" />, that doesn't work :)

Nick Craver
Doh, beat me to it. +1
GenericTypeTea
Yes, the key point here is that this has to be javascript in your aspx and NOT in your js file. ASP.Net will not execute the .js file unless you have specifically told IIS to do so, even then you will struggle to find the textbox.
Robin Day
+1  A: 

You cant access the txtTextBox.ClientID from your js-file becase its an ASP.Net Property. What are you doing with the textboxes' value? Consider giving the js-function the value or the reference to the textbox per parameter in this way(f.e. onchange-event):

<asp:TextBox ID="txtTextBox" runat="server" onchange="javascript: callFunction( this );" /> 

where callFuntion is your js-function in tools.js:

function callFunction( txtBox ){
   var txtBoxValue;
   if(txtBox != null)
       txtBoxValue = txtBox.value;
}

Regards, Tim

Tim Schmelter