我有一个带有OnTextChanged事件的asp:文本框,当我从绑定到它的jQuery日期选择器中选择一个新日期时我要触发该事件但是在选择日期时,OnTextChanged永远不会触发.如果我“手动”更改文本,它会触发,但我想强制用户从datepicker中选择日期.我需要在每次更改日期时运行服务器端代码.我已尝试在datepicker上使用onSelect方法,但无法让它调用该方法.
这是我的客户端代码:
function pageLoad() { $(".datepicker").datepicker({ constrainInput: true,dateFormat: 'dd D M yy' }); } <asp:UpdatePanel runat="server" ChildrenAsTriggers="True"> <ContentTemplate> <asp:TextBox ID="txtPickupDate" runat="server" OnTextChanged="txtPickupDate_TextChanged" CssClass="datepicker" AutopostBack="true" > </asp:TextBox> <asp:DropDownList ID="ddlPickupTime" runat="server" /> </ContentTemplate>
非常感谢任何帮助
更新:被要求包含TextChanged函数.最初没有发布,因为它没有触发方法,并认为它不会影响解决方案,但无论如何,这里是:
protected void txtPickupDate_TextChanged(object sender,EventArgs e) { DateTime pickupDate = DateTime.Parse(txtPickupDate.Text); //do things with the date }
解决方法
我测试了您的代码,并且在datepicker上选择日期时会触发TextChanged服务器端方法.
我做的一个小改动是重构jquery驻留在$(document).ready()函数中
<script type="text/javascript"> $(document).ready(function() { $(".datepicker").datepicker({ constrainInput: true,dateFormat: 'dd D M yy' }); }); </script>
请参阅下面的完整代码.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DatePickerTest.aspx.cs" Inherits="TestApp.DatePickerTest" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title></title> <script type='text/javascript' src='http://code.jquery.com/jquery-1.4.2.js'></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.js"></script> <link rel="stylesheet" type="text/css" href="/css/normalize.css"/> <link rel="stylesheet" type="text/css" href="/css/result-light.css"/> <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/themes/smoothness/jquery-ui.css"/> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="txtPickupDate" runat="server" OnTextChanged="txtPickupDate_TextChanged" CssClass="datepicker" AutopostBack="true"></asp:TextBox> </div> </form> <script type="text/javascript"> $(document).ready(function() { $(".datepicker").datepicker({ constrainInput: true,dateFormat: 'dd D M yy' }); }); </script> </body> </html>
和服务器端
protected void txtPickupDate_TextChanged(object sender,EventArgs e) { DateTime pickupDate = DateTime.Parse(txtPickupDate.Text); }
根据以下评论编辑:
要允许TextChanged事件在回发后继续触发,您可以使用
.live()如果不使用最新版本的jquery,现在是deprecated
$(function() { $('.datepicker').live('click',function() { $(this).datepicker({ constrainInput: true,dateFormat: 'dd D M yy' }).focus(); }); });
或.on()以及最新版本的JQuery 1.7及更高版本
$('body').on('click','.datepicker',function() { $(this).datepicker({ constrainInput: true,dateFormat: 'dd D M yy' }).focus(); });