2010-09-16 94 views
0

如何使用javascript访问母版页中的控件?母版页由一个搜索文本框组成,在控件的关键事件上,我调用母版页内嵌的javascript函数。我在那个javascript函数中获得了在文本框中输入的值。我试着给document.getElementById(“<%= txtSearch.ClientID%>”)。value以及document.getElementById(“txtSearch”).value。两者都显示错误。我必须从母版页本身访问文本框控件!在母版页中使用javascript在母版页中访问控件

+0

你得到了什么错误?什么浏览器版本? – 2010-09-16 12:25:29

+0

我正在使用IE 8浏览器。指定此代码时document.getElementById(“txtSearch”).value;我在浏览器中将'object required error'作为客户端错误消息。并指定document.getElementById(“<%= txtSearch.ClientID%>”)。值我得到'源代码不可用'警告消息,并在单击确定时,它显示服务器端错误'Controls集合不能被修改,因为该控件包含代码块(即<% ... %>)。' – banupriya 2010-09-16 12:29:40

+0

我指定了document.getElementById(“ct100_txtSearch”).value。只是一个临时修复!但是任何人都请建议如何使用代码动态获取此ID。我通过查看生成的页面的源代码来获得此信息。 – banupriya 2010-09-17 09:55:20

回答

1

我认为您在评论中显示的内容中缺少一些重要的标记。我试过了,下面的代码工作。检查一下,也许你会看到你的问题在哪里;否则,请解释您的标记在哪里不同。

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="WebApplicationDummy.SiteMaster" %> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> 
<head runat="server"> 
    <title></title> 
    <script type="text/javascript"> 
     function txtSearch_KeyDown() { 
      alert(document.getElementById('<%=txtSearch.ClientID %>').value); 
     } 
    </script> 
</head> 
<body> 
    <form runat="server"> 
    <table width="226" border="0" cellpadding="2" cellspacing="2"> 
     <tr> 
      <td width="150" align="right"> 
       <asp:TextBox ID="txtSearch" CssClass="para1Black" Width="180px" ValidationGroup="GlobalSearch" 
        runat="server" MaxLength="100" onkeydown="txtSearch_KeyDown()"></asp:TextBox> 
      </td> 
      <td width="62"> 
       <asp:ImageButton ID="imgbtnSearch" ToolTip="Click to search." ImageUrl="images/search2.jpeg" 
        CausesValidation="true" Width="22px" Height="22px" runat="server" ValidationGroup="GlobalSearch" /> 
      </td> 
     </tr> 
    </table> 
    <asp:ContentPlaceHolder ID="MainContent" runat="server" /> 
    </form> 
</body> 
</html>