jQuery Time Entry

A jQuery plugin that sets an input field up to pick a time value using a spinner. If you find this plugin useful please vote for it on the jQuery site.

Complement this plugin with the jQuery Datepicker plugin, for a popup calendar, the jQuery Calendars plugin, for support of other world calendars and a datepicker that works with them, or the jQuery Date Entry plugin, for spinner entry of dates.

The current version is 1.4.6 and is available under the GPL and MIT licences. For more detail see the documentation reference page. Or see a minimal page that you could use as a basis for your own investigations.

Default Settings

The time entry functionality can easily be added to an input field with appropriate default settings. Also shown is the control's appearance when disabled.

Default time entry:    

$('#defaultEntry').timeEntry().change(function() {
	var log = $('#log');
	log.val(log.val() + ($('#defaultEntry').val() || 'blank') + '\n');
});

On change log:

The defaults are:

You can enable or disable time entry fields.

$('#enableDefault').toggle(
	function() {
		$(this).text('Enable');
		$('#defaultEntry').timeEntry('disable');
	}, 
	function() {
		$(this).text('Disable');
		$('#defaultEntry').timeEntry('enable');
	});

Or completely remove the time entry functionality.

$('#removeDefault').toggle(
	function() {
		$(this).text('Re-attach');
		$('#defaultEntry').timeEntry('destroy');
	},
	function() {
		$(this).text('Remove');
		$('#defaultEntry').timeEntry();
	});

You can override the defaults globally as shown below:

$.timeEntry.setDefaults({show24Hours: true});

Processed fields are marked with a class of hasTimeEntry and are not re-processed if targetted a second time.

Keystrokes

The time entry field also responds to keystrokes.

Keyboard driven:

$('#keyedEntry').timeEntry();

The relevant keystrokes are:

Time Formats

You can control how the time is presented.

Show seconds:

$('#showSeconds').timeEntry({showSeconds: true});

Show 24 hour time:

$('#show24').timeEntry({show24Hours: true});

Separate AM/PM:

$('#separateAmpm').timeEntry({ampmPrefix: ' '});

Change the separator:

$('#showSeparator').timeEntry({separator: '.'});

No separator:

$('#noSeparator').timeEntry({separator: ''});

Interact with the inputs:

When setting the time you can provide a Date object, or a number for seconds from now, or a string containing the period and units: 'H' for hours, 'M' for minutes, or 'S' for seconds. Letters may be upper or lower case. Multiple offsets may be combined into the one setting. Prefix with '!' to prevent a wrap around into another day.

function getTheTime() {
	alert('The time is ' +
		$('#' + $('#pickInput').val()).timeEntry('getTime'));
}

function setTheTime() {
	var time = ($('#abs').is(':checked') ?
		new Date(0, 0, 0, 16, 7, 11) : '+1h +30m');
	$('#' + $('#pickInput').val()).timeEntry('setTime', time);
}

$('#getTheTime').click(getTheTime);
$('#setTheTime').click(setTheTime);

Time Restrictions

You can restrict the functionality of the time entry fields in various ways. The first example only allows selection of times in quarter hour increments by setting the steps for each of hours, minutes, and seconds.

Restricted time increments:

$('#restrictSteps').timeEntry({timeSteps: [1, 15, 0]});

You can also limit the range of times selectable within the field. Here it's between 8:30AM and 5:30PM.

Limited times:

$('#restrictRange').timeEntry({minTime: new Date(0, 0, 0, 8, 30, 0), 
	maxTime: new Date(0, 0, 0, 17, 30, 0)});

The range of selectable times can also be set as times relative to the current time. Use a number for seconds from now, or a string containing the period and units: 'H' for hours, 'M' for minutes, or 'S' for seconds. Letters may be upper or lower case. Multiple offsets may be combined into the one setting. Prefix with '!' to prevent a wrap around into another day.

Relative limited times:

$('#restrictRelative').timeEntry({minTime: -600, maxTime: '!+2h'});

Additional restrictions can be applied via a callback function that is called just before setting a new time for the field. Here only times in the first half of each hour are accepted.

Additional restriction:

$('#restrictTime').timeEntry({beforeSetTime: firstHalfHourOnly});

function firstHalfHourOnly(oldTime, newTime, minTime, maxTime) {
	var increment = (newTime - (oldTime || newTime)) > 0;
	if (newTime.getMinutes() > 30) {
		newTime.setMinutes(increment ? 0 : 30);
		newTime.setHours(newTime.getHours() + (increment ? 1 : 0));
	}
	return newTime;
}

Miscellaneous Features

To make it easier to use the spinner, you can set it to expand on hover.

Expanded spinner:

$('#expandedSpinner').timeEntry(
	{spinnerBigImage: 'img/spinnerDefaultBig.png'});

You can set which portion of the time should be initially highlighted. Use 0 for hours, 1 for minutes, etc.

Highlight minutes:

$('#highlightMins').timeEntry({initialField: 1});

You can set a default time to show when nothing has been selected. If this setting is not specified, it defaults to the current time.

Absolute default time:

$('#absoluteDefault').timeEntry(
	{defaultTime: new Date(0, 0, 0, 11, 11, 11)});

Alternatively, the default time can be set relative to the current time. Use a number for seconds from now, or a string containing the period and units: 'H' for hours, 'M' for minutes, or 'S' for seconds. Letters may be upper or lower case. Multiple offsets may be combined into the one setting. Prefix with '!' to prevent a wrap around into another day.

Relative default time:

$('#relativeDefault').timeEntry({defaultTime: '+1h +30m'});

Time Range

Use a custom field settings function to create a time range control: two time fields, each restricting the other. The function takes an input field as an argument and returns a settings object.

Time range: to

$('.timeRange').timeEntry({beforeShow: customRange});

function customRange(input) {
	return {minTime: (input.id == 'tTo' ?
		$('#tFrom').timeEntry('getTime') : null), 
		maxTime: (input.id == 'tFrom' ?
		$('#tTo').timeEntry('getTime') : null)};
}

Spinner Settings

Change the spinner. The first one has no central "Now" button, while the last has only the increment and decrement buttons.

Alternate spinners:

       

    

Specify the size of the new spinner image (width and height) along with the size of the central button (0 for none) so that the location of the individual "buttons" can be determined. Suppress the previous/next buttons with spinnerIncDecOnly.

$('#spinnerSquare').timeEntry({spinnerImage: 'img/spinnerSquare.png',
	spinnerSize: [20, 20, 0], spinnerBigSize: [40, 40, 0]});
$('#spinnerOrange').timeEntry({spinnerImage: 'img/spinnerOrange.png'});
$('#spinnerText').timeEntry({spinnerImage: 'img/spinnerText.png',
	spinnerSize: [30, 20, 8], spinnerBigSize: [60, 40, 16]});
$('#spinnerGem').timeEntry({spinnerImage: 'img/spinnerGem.png'});
$('#spinnerUpDown').timeEntry({spinnerImage: 'img/spinnerUpDown.png',
	spinnerSize: [15, 16, 0], spinnerBigSize: [30, 32, 0],
	spinnerIncDecOnly: true});
	
$('#expand').change(function() {
	var expanded = $(this).is(':checked');
	$('.spinners').each(function() {
		$(this).timeEntry('change',
			{spinnerBigImage: (expanded ? 'img/' + this.id + 'Big.png' : '')});
	});
});

Disable auto-repeat:

$('#disableRepeat').timeEntry({spinnerRepeat: [0, 0]});

No mouse wheel support:

$('#noMouseWheel').timeEntry({useMouseWheel: false});

No spinner image:

$('#noSpinnerEntry').timeEntry({spinnerImage: ''});

Inline Configuration

Instead of configuring time entry fields via parameters to the instantiation call, you can specify them inline. You must add the jQuery Metadata plugin to your page and then encode the settings in the class attribute (by default).

Inline configuration 1:

Inline configuration 2:

<input type="text" size="10" class="inlineConfig
	{show24Hours: true, timeSteps: [1, 30, 0], appendText: ' (see below)'}">
	
<input type="text" size="10" class="inlineConfig
	{minTime: new Date(0, 0, 0, 0, 0, 0), maxTime: new Date(0, 0, 0, 11, 59, 0)}">
$('.inlineConfig').timeEntry();

Or reconfigure on the fly.

Reconfiguration:

$('#reConfig').timeEntry({showSeconds: true});
$('#switchButton').toggle(
	function() { $('#reConfig').timeEntry('change', 
		{show24Hours: true, showSeconds: false}); },
	function() { $('#reConfig').timeEntry('change',
		{show24Hours: false, showSeconds: true}); }
);

Localisation

You can localise the time entry fields for other languages and regional differences. The time entry defaults to English with a time format of HH:MMAP. Select a language to change the time format and spinner tooltips.

:

You need to load the appropriate language package (see list below), which adds a language set ($.timeEntry.regional[langCode]) and automatically sets this language as the default for all time entry fields.

<script type="text/javascript" src="jquery.timeentry-fr.js"></script>

Thereafter, if desired, you can restore the original language settings.

$.timeEntry.setDefaults($.timeEntry.regional['']);

And then configure the language per time entry field.

$('#l10nTime').timeEntry($.timeEntry.regional['fr']);
$('#language').change(localise);

In the Wild

This tab highlights examples of this plugin in use "in the wild".

To add another example, please contact me (kbwood{at}iinet.com.au) and provide the plugin name, the URL of your site, its title, and a short description of its purpose and where/how the plugin is used.

Backwards Compatibility

Several interface changes were made between v1.2.6 and v1.3.0 to bring this plugin into line with the new UI interface standards.

To assist in the upgrade process, a compatibility module is available that allows a v1.2.6 page to be run against the latest code.

Just add the following line to your page after the plugin load to continue running:

<script type="text/javascript" src="jquery.timeentry.compat-1.2.6.js"></script>

To complete the upgrade perform the following steps:

Quick Reference

A full list of all possible settings is shown below. Note that not all would apply in all cases. For more detail see the documentation reference page.

$(selector).timeEntry({
	show24Hours: false, // True to use 24 hour time, false for 12 hour (AM/PM)
	separator: ':', // The separator between time fields
	ampmPrefix: '', // The separator before the AM/PM text
	ampmNames: ['AM', 'PM'], // Names of morning/evening markers
	// The popup texts for the spinner image areas
	spinnerTexts: ['Now', 'Previous field', 'Next field', 'Increment', 'Decrement']
	
	appendText: '', // Display text following the input box, e.g. showing the format
	showSeconds: false, // True to show seconds as well, false for hours/minutes only
	timeSteps: [1, 1, 1], // Steps for each of hours/minutes/seconds when incrementing/decrementing
	initialField: 0, // The field to highlight initially, 0 = hours, 1 = minutes, ...
	useMouseWheel: true, // True to use mouse wheel for increment/decrement if possible,
		// false to never use it
	defaultTime: null, // The time to use if none has been set, leave at null for now
	minTime: null, // The earliest selectable time, or null for no limit
	maxTime: null, // The latest selectable time, or null for no limit
	spinnerImage: 'spinnerDefault.png', // The URL of the images to use for the time spinner
		// Seven images packed horizontally for normal, each button pressed, and disabled
	spinnerSize: [20, 20, 8], // The width and height of the spinner image,
		// and size of centre button for current time
	spinnerBigImage: '', // The URL of the images to use for the expanded time spinner
		// Seven images packed horizontally for normal, each button pressed, and disabled
	spinnerBigSize: [40, 40, 16], // The width and height of the expanded spinner image,
		// and size of centre button for current time
	spinnerIncDecOnly: false, // True for increment/decrement buttons only, false for all
	spinnerRepeat: [500, 250], // Initial and subsequent waits in milliseconds
		// for repeats on the spinner buttons
	beforeShow: null, // Function that takes an input field and
		// returns a set of custom settings for the time entry
	beforeSetTime: null // Function that runs before updating the time,
		// takes the old and new times, and minimum and maximum times as parameters,
		// and returns an adjusted time if necessary
});

$.timeEntry.setDefaults(settings) // Set default values for all instances

$(selector).timeEntry('change', settings) // Change the settings for selected instances

$(selector).timeEntry('destroy') // Remove the time entry functionality

$(selector).timeEntry('disable') // Disable time entry

$(selector).timeEntry('enable') // Enable time entry

$(selector).timeEntry('isDisabled') // Determine if field is disabled

$(selector).timeEntry('setTime', time) // Set the time for the instance

$(selector).timeEntry('getTime') // Retrieve the currently selected time

Usage

  1. Include the jQuery library in the head section of your page.
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
  2. Download and include the jQuery Time Entry CSS and JavaScript in the head section of your page.
    <style type="text/css">@import "jquery.timeentry.css";</style>
    <script type="text/javascript" src="jquery.timeentry.js"></script>
    Alternately, you can use the packed version jquery.timeentry.pack.js (11.3K vs 35.7K) or minified version jquery.timeentry.min.js (16.2K, 5.1K after zipping).
  3. Connect the time entry functionality to your input controls.
    $(selector).timeEntry();
    You can include custom settings as part of this process.
    $(selector).timeEntry({show24Hours: true, showSeconds: true});

For more detail see the documentation reference page. Or see a minimal page that you could use as a basis for your own investigations.

Localisations

Localisation packages are available for download and should be loaded after the main time entry code. These packages automatically apply their settings as global default values.

Other translations are welcomed.

Comments

This is a very useful little widget, nice job!

Karen Stevenson

We've all been very happy with it and think it's an excellent intuitive way of gathering time input in an easy and concise fashion.

Jason Blumenkrantz

Thank you very much for your TimeEntry. It is incredibly useful, and I have been putting it in every form for time checking. Well done.

Vern Baker

Contact Keith Wood at kbwood{at}iinet.com.au with comments or suggestions.

Change History

VersionDateChanges
1.4.629 Aug 2009
  • Updated direct entry to allow more single digit values
  • Added localisations: Icelandic
1.4.504 Jul 2009
  • Changed inline configuration to work from metadata in class attribute
  • Ensure focus when mouse wheel is used
  • Added localisations: Japanese, Vietnamese
1.4.423 May 2009
  • Handle expanded spinner in relative container
  • Only trigger the field change event if the value actually changed
  • Corrected stealing of focus on spinner over/out
  • Corrected field highlighting on initial focus and with text alignment
  • Tuned sub-field determination in IE
1.4.314 Mar 2009
  • Added spinnerBigImage and spinnerBigSize settings for an on-demand expanded spinner
  • Renamed spinner images
  • Added localisations: Czech
1.4.207 Feb 2009
  • Added Google Chrome support
  • Corrected error when attaching to a non-visible field
  • Only restore focus if already there
1.4.129 Nov 2008
  • Corrected error in scroll position calculation
  • Added localisations: Turkish
1.4.012 Jul 2008
  • Internal changes for instance values
  • Added beforeSetTime setting to allow for further restrictions before updating time
1.3.107 Jun 2008
  • Added defaultTime setting
  • Allow setTime command and defaultTime option to use relative times
  • Fix bug in keystroke entry in 12-hour mode for PM hours
  • When already in a field, click selects underlying field
  • Clone datetime used in set time
  • Remove FF CSS patch for v3
  • Added localisations: Dutch
1.3.023 Feb 2008
  • Updated interface to conform to jQuery UI standards
  • Added 'destroy' command
  • Added initialField setting
  • Added backwards compatibility module for v1.2.6
1.2.629 Dec 2007
  • Corrected handling of time entry controls in fixed areas
  • Made button images transparent
1.2.513 Oct 2007
  • Spinner images now include disabled view
  • Renamed timeEntry object to $.timeEntry
  • Renamed fieldSettings setting to beforeShow
  • Enhance parameters for getTimeFor, setTimeFor and isDisabled
  • Added localisations: Portugese
1.2.429 Sep 2007
  • Upgraded to work with jQuery 1.2
  • Corrected spinner clicks when scrolled
  • Corrected spinner switching when clicked
  • Corrected Chinese localisation
  • Added localisations: Swedish
1.2.314 Sep 2007
  • Dual licenced GPL and CC
  • Corrected for new extend "feature" in latest jQuery releases
  • Processed fields marked with hasTimeEntry class and won't be re-processed
  • Added localisations: Romanian, Slovak, Spanish
1.2.201 Sep 2007
  • Changed spinner image to contain all pressed images in one
  • Spinner images converted to PNG
  • Removed spinnerPath and spinnerClickImages attributes
  • Added spinnerIncDecOnly attribute
  • Added localisations: Simplified Chinese, Italian, Hungarian, Polish, Russian
  • Fixed Opera bugs
1.2.111 Aug 2007
  • Renamed package to jquery.timeentry.* to follow jQuery conventions
  • Hid time entry declarations - functionality is only accessible via timeEntry
  • Added ampmPrefix and useMouseWheel attributes
  • Added mouse wheel increment/decrement support (with jquery.mousewheel.js)
  • Allow double click to select a time sub-field
  • Added handling for paste events to validate entry
  • Trigger input field's onchange event when the time is updated
  • Added more spinner examples
  • Added German localisation
1.2.028 Jul 2007
  • Rewritten to allow multiple instances on a page each with different settings
  • Allow for inline configuration of the time entry instance from attributes on the input
  • Added setDefaults(), reconfigureFor(), setTimeFor(), getTimeFor(), spinnerPath
1.1.213 Jul 2007
  • Fixed bug in calculating spinner position
1.1.128 Jun 2007
  • Fixed bug in time parsing for 12AM/PM
1.127 Jun 2007
  • Added enable/disable handling
  • Added fieldSettings attribute to allow customisation per field
  • Added spinner auto-repeat on the increment and decrement buttons
  • Added alternate images when a spinner "button" is clicked
1.020 Jun 2007
  • Initial release