YUI: Using Event.addListener. One Calendar, Multiple Fields

I am working on a YUI application where I have multiple date fields. The date fields are regular input fields. When a user clicks on the input field a YUI Calendar appears. When a date is selected from the calendar, the date value is inserted into the appropriate input field.

To set up multiple input fields to use one calendar, I first created a variable and set it to null:

var clickEl = null;

I then used an Event Listener (Event.Listener) using the ids of the input fields:

var ids = ["appoint_date", "interp_date", "service_date", "cancel_date"];
Event.addListener(ids, "click", showCal);

When a user clicks on one of the input fields, the showCal function is called. The showCal function sets the clickEl variable to the id of the “clicked” input field and then shows a YUI Dialog component that contains the YUI Calendar.

function showCal(e) {
     clickEl = this.id;

When a date is selected, the date value is inserted into the appropriate input field:

var selDate = calCal.getSelectedDates()[0];
var dStr = selDate.getDate();
var mStr = calCal.cfg.getProperty("MONTHS_SHORT")[selDate.getMonth()];
var yStr = selDate.getFullYear();
Dom.get(clickEl).value = yStr + "-"+ mStr + "-" + dStr;

Of course the alternative is to create a separate calendar for each input field. Too much work (and obviously not necessary). Enjoy.

Be Sociable, Share!

Checkout My New Site - T-shirts For Geeks