How to add a date time picker using jQuery?

I thought the jQuery library must have supported the calendar/date time picker UI because it is such a basic and frequently used control like button or input box. But I’m wrong, there is no such function included in jquery.js. You’ll find another library that provides the data time picker. That is called jQuery plugin and separated from the main jquery js file.  And annoying enough that plugin just does not work if you download it from its official website. The downloaded zip file is extracted to a folder which contains a lot of files and sub-folders. There is no readme in it. You just do not know how to use the datetimepicker plugin. By doing some research, I got to know if you want to use the jquery datetimepicker plugin, you need to include the files jquery.datetimepicker.js, jquery.datetimepicker.css that are provided by the plugin apart from the juery main file jquery.js. The usage of the plugin itself is not complex:

<input type="text" maxlength="30" size="18"  id="time" onclick="$('#time').datetimepicker();">

You just need to select the element you want to display a date time picker at, then call the datetimepicker() function.  But as I said, the downloaded js file from its official website does not work. It will tell you the error:”TypeError:dateHelper is null“. Finally, I got this file and it solved my problem.

datetimerpicker
datetimerpicker

Now, when I click on the input box, the calendar appears. I can click on a date to select it, and the date will appear in the input box. When I click a time, the selected time also appears in the edit box, then the calendar window closes.

Let’s look into the data time picker plugin a little further. After introducing the js file(jquery.datetimepicker.js) of the plugin, a new object is created in the juery object $, i.e.,$.datetimepicker. You can do some settings on this object, which are global settings, i.e., applied to every datetimepicker on the web page. For example, you can set the language of this control to Chinese:

$.datetimepicker.setLocale('ch');

All the date time pickers on the web page will display Chinese on their interface. But you cannot use $.datetimepicker to display a UI. As I said, you should select an element to display the UI on it using the datetimepicker() function. This function has an option parameter which can be used to customize the UI. For example, we can set the minimum or maximum date that is allowed to pick thru the control.

var today=new Date();
var laterday=new Date();
laterday.setDate(laterday.getDate()+3);
$.datetimepicker.setLocale('ch');
var opt=
{
  minDate:today,
  maxDate:laterday
};
$('#time').datetimepicker(opt);

In the above example, we can only select a day within today and 3 future days. The other dates on the calendar are greyed out and prohibited from selecting.

 

 

 

Comments are closed, but trackbacks and pingbacks are open.