Search code examples
javascriptasp.netwebformsdatepickerpikaday

ASP.NET Pikaday don't work with master page


In a simple web form Pikaday works nice but when I'm using this in a content page it doesn't work, for better understanding I'm giving the code......Thanks in advance

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="Test2.Site1" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="css/pikaday.css" rel="stylesheet" />
    <link href="css/theme.css" rel="stylesheet" />
    <script src="js/pikaday.js"></script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
            </asp:ContentPlaceHolder>
        </div>
    </form>
</body>
</html>

and content page code

<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="ContentPage.aspx.cs" Inherits="Test2.WebForm2" %>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
     <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <h4>This is from content page</h4>
            <asp:TextBox ID="tbxFromDate" runat="server"></asp:TextBox>
            <asp:TextBox ID="tbxToDate" runat="server"></asp:TextBox>

            <script type="text/javascript">
                var picker1 = new Pikaday({
                    field: document.getElementById('tbxFromDate'),
                    theme: 'dark-theme'
                });
                var picker2 = new Pikaday({
                    field: document.getElementById('tbxToDate'),
                    theme: 'dark-theme'
                });
            </script>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

I don't understand what I'm missing


Solution

  • The problem is that tbxFromDate and tbxToDate do not exist in the HTML. Because the Controls are in a Content Control, their ID's are changed to ensure there are no duplicates.

    Their ID probably looks something like this: ContentPlaceHolder1_tbxFromDate.

    So you need to reference them by their ClientID. So use

    <script type="text/javascript">
        var picker1 = new Pikaday({
            field: document.getElementById('<%= tbxFromDate.ClientID %>'),
            theme: 'dark-theme'
        });
        var picker2 = new Pikaday({
            field: document.getElementById('<%= tbxToDate.ClientID %>'),
            theme: 'dark-theme'
        });
    </script>