Search code examples
jqueryasp.nettextboxcalendarextender

Setting TextBox.Text after Selecting a Date on an Ajax CalendarExtender


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));
    }
}

Solution

  • 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");