Binding Calendar to a Form Field
The Calendar component can be bound to an input field using the JavaScript API. We'll take a look here at how to incorporate this functionality.
The HTML Declaration
The declaration for the component is quite simple:
<ntb:datepicker id="cal1" ondateselected="populateDateField(this)"> <ntb:calendar></ntb:calendar> <ntb:dateinput></ntb:dateinput> </ntb:datepicker>
We must supply an id attribute to ensure the component loads properly. We use the ondateselected attribute to supply a custom event handler that will eventually fill the form field with a date value. Note that we pass this to populateDateField; it is a reference to the Calendar JavaScript object.
The JavaScript Code
From the markup above we see we have just one function to define: populateDateField.
populateDateField()
We see here that we use the Calendar's getSelectedDate() method to return a JavaScript date and we call toString() on that object to get a properly formatted date that will look like this: Thu Nov 08 2007 00:00:00 GMT-0800 (Pacific Standard Time). Additionally, this full date string is chopped at the time information to yield only the calendar date.
function populateDateField(calendar) { var date = calendar.getSelectedDate().toString(); $('dateField').value = date.substring(0, date.indexOf("00:00:00")); }
Sample HTML Source Code
Here is the full tutorial HTML code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ntb="http://www.nitobi.com"> <head> <script type="text/javascript" src="script/nitobi.toolkit.js"></script> <script src="script/nitobi.calendar.js" type="text/javascript"></script> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Calendar Demo</title> <link href="style/nitobi.calendar.css" rel="stylesheet" type="text/css" /> <script type="text/javascript"> <!-- nitobi.html.attachEvent(window,"load",function(){nitobi.loadComponent("cal1")}); //--> </script> <script> function populateDateField(calendar) { var date = calendar.getSelectedDate().toString(); $('dateField').value = date.substring(0, date.indexOf("00:00:00")); $('calendarContainer').style.display = "none"; } </script> </head> <body> <input id="dateField" type="text" > <ntb:datepicker id="cal1" width="180px" height="192px" ondateselected="populateDateField(this)"> <ntb:calendar></ntb:calendar> <ntb:dateinput></ntb:dateinput> </ntb:datepicker> </body> </html>
Comments
page_revision: 4, last_edited: 1246401468|%e %b %Y, %H:%M %Z (%O ago)
Hey guys,
This tutorial looks to be out of date. I think there was a post to the google group due to confusion from this tutorial.
Thanks for the comment, mhan. I have updated the tutorial accordingly.