Using the EXT JS Date Picker Widget - Finishing the Example
(Page 3 of 4 )
So far so good, but we don’t want the widget to be visible as soon as the page loads; we want it to remain hidden until the button for it is clicked. There are several ways in which this could be achieved. The simplest way of doing this is probably to hide the date picker directly after it has been rendered and then to show it again when the button is clicked. Add the following code directly after the call to the render method:
//hide date picker straight away
myDP.hide();
//define click handler
var clickHandler = function() {
//show the date picker
myDP.show();
};
//add listener for button click
Ext.EventManager.on('openCalendar', 'click', clickHandler);
The hide method does exactly what it says on the tin; it hides the date picker instance it is being called on. Following this, we define a callback function which simply shows the specified date picker instance. Finally we make use of a totally different class of the library, the event manager. This singleton class doesn’t need to be instantiated in the same way as the date picker widget; we can just call its methods as and when we need them. In this case we use the on method, which allows us to define an event handling callback function (the function we just defined) on a specified event fired by a specified element. Now when you run the page, the date picker will initially be hidden until the button is clicked.
All that remains now is for us to get the date is selected and add it to the text box. To do this we need to add some more code near the top of the code. Right at the start of the onReady function add the following code:
//define select handler
var selectHandler = function(myDP, date) {
//get the text field
var field = document.getElementById('dateField');
//add the selected date to the field
field.value = date.format('d/m/Y');
//hide the date picker
myDP.hide();
};
This event handler first gets a representation of the text field, then updates its value with the date that is returned by the date picker object. This date will equal whatever date was selected in the date picker. As it is a full UTC date we need to format it to the more usable form of dd/mm/yyyy using the format method (note that this method is part of the Date class, not part of the DatePicker class). Once the date has been added to the text field we can close the date picker.
In order to call this function at the appropriate time we need to make use of one the date picker’s custom events. A wide range of different custom events are defined for the date picker which fire at different times during its execution, such as when it opens, when it closes and when a date is selected. This is the event that we will be using in this example – the select event.
Next: Finishing continued >>
More JavaScript Articles
More By Dan Wellman