Access a control in master page using javascript within the master page itself

asp.net

How to access controls in master page using javascript? The master page consists of a search textbox, on key down event of the control I call a javascript function writtern inline of the master page. I get the value of entered in textbox in that javascript function. I have tried giving document.getElementById("<%=txtSearch.ClientID %>").value as well as document.getElementById("txtSearch").value. Both display error. I have to access the textbox control from within the master page itself!

Best Answer

I think some important bits of markup are missing from what you showed in the comment. I tried it, and the following code works. Check it out, maybe you'll see where your problem is; otherwise, please explain where your markup is different.

<%@ 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>
Related Topic