jQuery Auto Datepicker

Posted 27 days ago

I somewhat recently started using jQuery datepicker in place of the dhtml_calendar Rails plugin. The change was for various reasons which are beyond the purpose of this blog. After using it a few times I realized it would be nice if I could just set a class on my text field and it would automagically become a jQuery datepicker enabled text field. Of course I am sure someone has likely already conquered this, I thought it would be a fun learning experience to write my own.

if (typeof jQuery != 'undefined' && typeof jQuery.datepicker != 'undefined') {
  $(window).load(function() {
    jQuery(".datepicker[id]").map(function(i) { $("#"+this.id).datepicker(); }); 
  }); 
};

Since I am using these to almost always store into a database I like to set the default date format.

if (typeof jQuery != 'undefined' && typeof jQuery.datepicker != 'undefined') {
  $(window).load(function() {
$.datepicker.setDefaults({ 
      "buttonImage" : "/images/calendar-icon.png",
      "constrainInput": false ,
      "dateFormat" : "yy-mm-dd", 
      "showAnim" : "slideDown", 
      "showOn" : "button"
      });
};

I am also overriding some other default options, using showOn and buttonImage I change the behavior of the datepicker to use an image of my choice to activate the calendar instead of the field itself. I change the animation to slideDown, personally I just think it looks a little more slick. I do not normally turn off constrainInput, since it adds another level of validation but in some cases it may be necessary so I thought it would be useful to demonstrate. Without disabling input constraint by setting constrainInput to false jQuery datepicker will not allow any characters that are not included in the defined format.

Hopefully this will prove helpful to someone, and if not I learned a little by doing it. I certainly welcome any feedback or constructive criticism or general cursing of my code.

After some real world use I realized my conditions were not properly ensuring that jQuery and jQuery.datepicker were available. IE was sure to make me aware of this. Anyway, the code is revised, I still feel that there must be a better way but in the infancy of my jQuery powers this is the solution I have turned out.

Posted in  | Tags , , ,  | no comments

Comments

(leave url/email »)

   Comment Markup Help Preview comment