Preventing a user from deselecting dates in a DateChooser control

by Peter deHaan on August 15, 2007

in DateChooser

Here’s an example which prevents users from deselecting a date in the Flex DateChooser control by Ctrl-clicking on the date. By listening for the DateChooser control’s change event, and if the currently selected date is null, we set the selected date to the previously selected date. Also, for no good reason, I added a List control which lets you disable certain dates in the calendar.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/08/15/preventing-a-user-from-deselecting-dates-in-a-datechooser-control/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            import mx.events.CalendarLayoutChangeEvent;

            private function dateChooser_change(evt:CalendarLayoutChangeEvent):void {
                /* Prevent deselecting of dates. */
                if (evt.currentTarget.selectedDate == null) {
                    evt.currentTarget.selectedDate = evt.newDate;
                }
            }
        ]]>
    </mx:Script>

    <mx:Array id="weekDayNames">
        <mx:String>Sun</mx:String>
        <mx:String>Mon</mx:String>
        <mx:String>Tue</mx:String>
        <mx:String>Wed</mx:String>
        <mx:String>Thu</mx:String>
        <mx:String>Fri</mx:String>
        <mx:String>Sat</mx:String>
    </mx:Array>

    <mx:String id="selDate">{dateChooser.selectedDate.toDateString()}</mx:String>

    <mx:HBox>
        <mx:VBox>
            <mx:DateChooser id="dateChooser"
                    disabledDays="{disabledDaysList.selectedIndices}"
                    selectedDate="{new Date()}"
                    dayNames="{weekDayNames}"
                    yearNavigationEnabled="true"
                    change="dateChooser_change(event)" />

            <mx:Label text="Selected date: {selDate}" />
        </mx:VBox>

        <mx:VBox>
            <mx:Label text="Disabled days:"    />
            <mx:List id="disabledDaysList"
                    width="100"
                    dataProvider="{weekDayNames}"
                    allowMultipleSelection="true" />
        </mx:VBox>
    </mx:HBox>

</mx:Application>

View source is enabled in the following example.

Leave a Comment

Sorry, this blog is terrible at eating HTML comments.
If you're pasting any HTML/XML/MXML code, you need to convert your < characters to &lt; and your > characters to &gt; .

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Anti-Spam Protection by WP-SpamFree

Previous post:

Next post: