YUI: Using Event.addListener. One Calendar, Multiple Fields
Friday, April 10th, 2009I 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; dlgCal.show(); } |
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.



October 16th, 2009 at 9:43 pm
[...] I first began the project, I created an event listener (Event.Listener) as discussed in a previous post. But, because a date field is fairly common in web applications, I wanted to create a widget so [...]
May 12th, 2010 at 5:42 am
This is really helpful….
Are you able to provide example code ?
May 12th, 2010 at 7:38 am
I actually created a widget.
I explain how to use it in this post: YUI: An Input Field Calendar Widget
Demo is here: YUI Widgets
Can be downloaded from Google Code: imAjaxWidgets
May 13th, 2010 at 2:05 pm
Thank you for this.
It helps in a anyway, although what I am after is a solution to providing a calendar for multiple fields with field names built within a recordset loop, the recordset row total varies accounting to SQL criteria and therefore in some case there may only be 5 date fields and in other perhaps 50 or 60, as in example code ….
<input type="text" id="” class=”DateField” name=”" value=”"size=”8″>
I am guessing the solution is in your code var ids = ["tDate1", "tDate2"]; perhaps there is a way to dynamically grow the ID variables within some kind of array or way to build var id names in a loop within the javascript as many times as a recordset total row count value passed to the script.
I don’t know really as I am no Javascript expert.
Thank you for any help you can give in advance.