I just wasted an hour trying to figure out how to simply set the date 
for a datepicker from within code.  So I'm posting what I've learned 
here hoping that I might save someone that hour themselves...

What I was trying to do was to simply show a default date in my text 
box.  I wanted to use the datepicker's methods so that a) I would have 
the same format as the results, and b) I wouldn't need to worry about 
creating a custom format method for the default that may or may not 
create a format that would work properly with the datepicker.

The sample pages do not seem to have this demonstrated (it's late, so 
maybe I just missed it).

Turns out the documentation is kinda correct.  Doing this DOES work:

$.datepicker.setDateFor("#mytextbox", new Date());

But what it doesn't do is actually SHOW the date in your text box.  To 
do that you have to do this:

$("#mytextbox").val(
   $.datepicker.formatDate(
     "dd M yy",
      $.datepicker.getDateFor("#mytextbox")
   )
);

(NOTE, that should be one line, I broke it down so it would render half 
decent in my mail client that auto wraps text at 80 chars...)

Doing the getDateFor() method does NOT honor the date format you've set 
for the date picker.  This makes sense because you're likely to be doing 
calculations on this date and getting a raw date object back is best for 
that.  So you have to take the date you retrieved and then filter it 
through the formatDate() method.

My thoughts are that the setDateFor() method should update the related 
textbox.  I can't think of any instances where this would cause problems 
(but it's late, and I'm tired.. :)

So, hopefully this rambling post will help someone else trying to do the 
same.

As an aside, I'm VERY happy to see the new formatting and parsing 
options.  Good work Marc!

Shawn

Reply via email to