问题
This is a follow up question from ASP.NET with jQuery DatePicker
I tried to use the jQuery UI DatePicker as suggested in this page: http://www.aspsnippets.com/Articles/jQuery-UI-DatePicker-Calendar-Example-in-ASPNet.aspx
When I tested the codes in a SINGLE webform, it works like a charm.
However, when I tried to incorporate them with Masterpage and Contentpage, I can't seem to make the calender working again.
This is what I have attempted so far:
In the Masterpage, I added the script scr and link in the Head:
<head runat="server">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title><%: Page.Title %> - My ASP.NET Application</title>
<asp:PlaceHolder runat="server">
<%: Scripts.Render("~/bundles/modernizr") %>
</asp:PlaceHolder>
<webopt:bundlereference runat="server" path="~/Content/css" />
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<%--added below--%>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="Stylesheet" type="text/css" />
</head>
Here is part of my codes in the Contentpage
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Test2._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
$(function () {
$("[id$=txtDate]").datepicker({
showOn: 'button',
});
});
</script>
<asp:TextBox ID="txtDate" runat="server" ReadOnly="true" Width="250px"></asp:TextBox>
What exactly have I missed?
回答1:
When you use master pages, each control that is specified with runat="server" will not actually have the ID you assign it. You can see the ID it has if you view the generated page source.
To get the actual ID, try doing this:
<script type="text/javascript">
$(document).ready(function () {
$("#<%= txtDate.ClientID %>").datepicker({
showOn: 'button',
});
});
</script>
<asp:TextBox ID="txtDate" runat="server" ReadOnly="true" Width="250px"></asp:TextBox>
If you're using UpdatePanels and you keep seeing your control getting unbound, replace $(document).ready(function (){ ... }); with function pageLoad() { ... }.
Make sure the JavaScript is at the end of your content/body tag as well. This will ensure it gets loaded last after all the page controls.
So it should be something like
// all my page content ...
<script type="text/javascript">
//sweet JS
</script>
</asp:Content>
来源:https://stackoverflow.com/questions/23788212/jquery-datepicker-not-working-with-masterpage