问题
On an ASP.NET page, I have a pair of CalendarExtender
(AJAX Control Toolkit for ASP.NET 4.0) controls on a page acting as a date range. What I want to do is, after the user has selected the value for TextCheckInDate
, populate TextCheckOutDate
with TextCheckInDate+ 1
if TextCheckOutDate
is empty.
Regrettably, my jQuery skills aren't yet where I'd like them to be. I know that I have to create a jQuery function that's fired when TextCheckInDate
changes, I need to be able to read both textboxes, perform basic date arithmetic and write to the second textbox. The implementation eludes me. Thanks to this post, I know to use date.js for my date arithmetic, included below...
What I have so far:
$("input[id$='TextCheckInDate']").keyup
(function (e) {
checkCheckOutDate( $("#TextCheckInDate").val() );
}
);
function checkCheckOutDate(checkInDate) {
var startDate = Date.parse(checkInDate);
if ($("#TextCheckOutDate").val() == "") {
$("#TextCheckOutDate").val((1).days().after(startDate));
}
}
回答1:
Can you prohibit to enter text into date textboxes? If so, you can use following approach:
<script type="text/javascript">
function checkInDateChanged(sender, args) {
var checkInDate = sender.get_selectedDate();
var checkOutDateExtender = $find("CheckOutdateExtender");
var checkOutdate = checkOutDateExtender.get_selectedDate();
if (checkOutdate == null || checkOutdate < checkInDate) {
checkOutdate = new Date(checkInDate.setDate(checkInDate.getDate() + 1));
checkOutDateExtender.set_selectedDate(checkOutdate);
}
}
</script>
<asp:TextBox runat="server" ID="TextCheckInDate" />
<ajax:CalendarExtender runat="server" ID="CheckInDateCalendarExtender" TargetControlID="TextCheckInDate"
OnClientDateSelectionChanged="checkInDateChanged" />
<asp:TextBox runat="server" ID="TextCheckOutDate" />
<ajax:CalendarExtender runat="server" ID="CheckOutDateCalendarExtender" BehaviorID="CheckOutdateExtender"
TargetControlID="TextCheckOutDate" />
in PreRender method add code below:
TextCheckInDate.Attributes.Add("readOnly", "readonly");
TextCheckOutDate.Attributes.Add("readOnly", "readonly");
回答2:
You should just be able to tweak your code slightly to also fire your checkCheckOutDate()
function when the checkin textbox's change
event fires.
$("input[id$='TextCheckInDate']").bind('keyup,change', function (e) {
checkCheckOutDate( $("#TextCheckInDate").val() );
});
function checkCheckOutDate(checkInDate) {
var startDate = Date.parse(checkInDate);
if ($("#TextCheckOutDate").val() == "") {
$("#TextCheckOutDate").val((1).days().after(startDate));
}
}
Note that lots of the event methods in jQuery like click()
, keyup()
, etc are just wrappers around bind('click', function() { ... })
.
来源:https://stackoverflow.com/questions/6273009/setting-textbox-text-after-selecting-a-date-on-an-ajax-calendarextender