Tomas Vinter
Tomas Vinter

Reputation: 2691

How to retrieve value from asp.net textbox from javascript?

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?

Upvotes: 1

Views: 15814

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460288

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

Upvotes: 2

Nick Craver
Nick Craver

Reputation: 630607

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 :)

Upvotes: 5

Related Questions