Monday, 9 July 2012

Using jQuery datepicker with html5 contenteditable


You are supposed to use jQuery datepicker with an input element.
Trying to attach it to a div gives a stay open calendar.
The trick here is to attach the datepicker to a hidden input element.

Use the "trigger by button" feature (hence little 'calendar' graphic)

When the datepicker closes (onClose) the new value can be planted (.html() )  in the visible contenteditable element.

If you are watching "on focus" & "on blur" of the contenteditable (to catch user editing) then these events can be simulated as the value is entered (.focus() - .blur() ) so that the change in date is dealt with as if the user entered it themselves.

HTML code:

<div>
<span class='date' contenteditable='false'>9/7/2012</span>
<input type='hidden' class='datepicker' />
</div>
Javascript code:

$(".datepicker").datepicker({
  dateFormat: 'dd/mm/yy',
  showOn: "button",
  buttonImage: "images/calendar.gif",
  buttonImageOnly: true,
  onClose: function(dateText, inst) {
  $(this).parent().find("[contenteditable=true]").focus().html(dateText).blur();
  }
});