admin管理员组

文章数量:1290941

I have an asp web form with a couple of asp 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?

I have an asp web form with a couple of asp 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?

Share Improve this question asked May 5, 2010 at 9:58 Tomas VinterTomas Vinter 2,6919 gold badges36 silver badges45 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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

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

本文标签: How to retrieve value from aspnet textbox from javascriptStack Overflow