我有一个带有几个asp.net文本框控件的asp.net Web表单:
<asp:TextBox ID="txtTextBox" runat="server" /> .
我有一个包含在页面中的javascript文件tools.js:
<script src="tools.js" type="text/javascript"></script>
如何从javascript访问txtTextBox中的值?
我尝试过使用
document.getElementById('<%= txtTextBox.ClienID %>').value;
document.getElementById('<%= txtTextBox.UniqueID %>').value;
document.getElementById('<%= txtTextBox %>').value;
但它们都不起作用。
有什么想法吗?
答案 0 :(得分:5)
你错过t
(正确!)解决方案:)上的ClientID
,如下所示:
document.getElementById('<%= txtTextBox.ClientID %>').value;
请注意,上述代码必须在页面中 ,因此它会打印出来给客户端:
document.getElementById('txtTextBox').value;
//or if it's deeper:
document.getElementById('Parent_txtTextBox').value;
如果它在外部js中,那么它会像这样打印出来,而不会替换<%= %>
部分:
document.getElementById('<%= txtTextBox.ClientID %>').value;
由于没有<input id="<%= txtTextBox.ClientID %>" />
,这不起作用:)
答案 1 :(得分:2)
你无法从你的js文件访问txtTextBox.ClientID,因为它是一个ASP.Net属性。你对文本框的价值做了什么? 考虑以这种方式为每个参数赋予js-function值或对文本框的引用(例如,onchange-event):
<asp:TextBox ID="txtTextBox" runat="server" onchange="javascript: callFunction( this );" />
其中callFuntion是tools.js中的js-function:
function callFunction( txtBox ){
var txtBoxValue;
if(txtBox != null)
txtBoxValue = txtBox.value;
}
此致 添