I’m using jquery-ui datepicker on a User DOB field in a Rails 3.2 app.
I’m trying to achieve the following:
- restrict the range of dates that can be selected, max = today, min = 100 years ago.
- initialize the datepicker with the date currently stored in the database (if any).
- display the selected date in a particular format in the dob text field.
My form looks like this:
<%= form_for @user do |f| %>
<%= f.text_field :dob, :class=>'date-selector-dob', :value => (@user.dob.blank? ? '' : @user.dob.to_s(:long)) %>
<% end %>
where .to_s(:long) is the display format I’m after.
With the following javascript the datepicker works, the text field is properly formatted, but no max/ min date is set, and no initialization with the stored date occurs.
$(function (){ // enabledate picker
$('.date-selector-dob').datepicker();
});
I added to this functions that I though would set min/max range and initialize, as follows:
$(function (){ // enable date picker
$('.date-selector-dob').datepicker({minDate: new Date('-100Y'), maxDate: new Date('-1D')}); // enable datepicker and set range
$('.date-selector-dob').datepicker('setDate', new Date($('.date-selector-dob').attr('value'))); // initialize datepicker with stored value
});
This is initializing the date picker correctly, but is not setting a min/max range. Is my approach incorrect?
In addition, the extended function resets my formatting string, and data is not displayed according to .to_s(:long). Using the basic function above, this formatting string is properly applied. What would cause this?
I’m pulling my hair out with this! I’d really appreciate it if someone can help me see whatever is it I’ve missed, and understand what I’m doing wrong. Thanks!
JavaScript’s
Datedoesn’t know what-100Yor-1Dmean so yourminDateandmaxDatesettings aren’t going to be anything that the datepicker will understand.From the fine manual:
So you want this:
Demo: http://jsfiddle.net/ambiguous/RQgCW/
If you want the datepicker to use a certain format for the date, use the
dateFormatoption:Also, you should be able to skip this:
and just set the
<input>‘svalueattribute to the date (preferably in ISO 8601 format), then the datepicker should be able to take it from there on its own.