YUI Library Home

YUI Library Examples: Calendar Control: Calendar and Text Fields

Calendar Control: Calendar and Text Fields

This example builds upon the Events example, by demonstrating how you can use the select event to set the state of a text box on the page.

It also demonstates how to limit the dates which can be selected using the mindate/maxdate properties and how the current page and selected date can be set on the Calendar after it is first rendered.

Setting up the Calendar

In this example, we will build a Calendar that can accept selections on any date from 1/1/2009 to 12/31/2013, and we will set up a text field that will be updated whenever the Calendar's selected date is changed. In addition, we will provide a button that can be used to update the Calendar with whatever date the user types into a text field provided on the page.

First, we will construct the Calendar with the minimum and maximum dates specified:

Next, we will place our markup, which includes a standard container for the Calendar, and the form with a text field and button:

Now, we must define a handler that will fire when the user changes the selected date on the Calendar. This function will be named handleSelect, and will be subscribed to the Calendar's selectEvent:

The handleSelect function receives an array of selected dates as an argument. Since this Calendar is only single-select, we will only need to retrieve the first (and only) item in the array. The date argument is passed as an easily sorted Integer array in the format: [yyyy, mm, dd]. The handleSelect function takes these values and prints them into a text field which we will define in a later step. It's also necessary to subscribe the function to the selectEvent on the Calendar so that it will be fired when a selection is made.

Next, we will define a function called updateCal, which will be used to update the Calendar with the value that is typed into the text field. This function will be called via a button that will be created in our markup a little later.

Note that on line 7 we test whether or not any dates are actually selected after calling the select() method, since the date the user is trying to select may lie outside the min/max dates defined for the Calendar in which case the Calendar's selected date will not be changed (and a selectEvent will not be fired).

The updateCal function does two key things. First, it grabs the value from the text field and uses it to make a new selection on the Calendar. Next, it changes the visible page of the Calendar to the Calendar's earliest selected date, so that the selection will be clear to the user.

Configuration for This Example

You can load the necessary JavaScript and CSS for this example from Yahoo's servers. Click here to load the YUI Dependency Configurator with all of this example's dependencies preconfigured.

Copyright © 2011 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings