In this article I will explain how to use the jQuery UI DatePicker plugin with the ASP.Net TextBox Control.
Applying the jQuery DatePicker to ASP.Net TextBox
Below is the HTML Markup used for this article.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<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" />
<script type="text/javascript">
$(function () {
$("[id$=txtDate]").datepicker({
showOn: 'button',
buttonImageOnly: true,
buttonImage: 'http://jqueryui.com/demos/datepicker/images/calendar.gif'
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="txtDate" runat="server" ReadOnly = "true"></asp:TextBox>
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" />
</form>
</body>
</html>
Above you will notice that I have added an ASP.Net TextBox control and an ASP.Net Button control. Also I have inherited the jQuery scripts and CSS style sheets for the jQuery DatePicker.
In the document ready event of jQuery I am applying the DatePicker plugin to the ASP.Net TextBox using the [id$=txtDate] jQuery Selector so that even if the ClientID of the Control changes it will not affect the jQuery code.
Fetching the values server side
In order to show how to fetch the value of the TextBox server side I have added a button btnSubmit with a click event handler.
C#
protected void btnSubmit_Click(object sender, EventArgs e)
{
string dt = Request.Form[txtDate.UniqueID];
}
VB.Net
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs)
Dim dt As String = Request.Form(txtDate.UniqueID)
End Sub
Above I am making use of Request.Form instead of the normal Text property because in some browsers changes done via client side scripts are not reflected server side and can cause problems. Hence to avoid that it is better to go for Request.Form collection as it will always contain the values during form submission.
Downloads
You can download the sample source code in C# and VB.Net using the download link provided below.