DaveInFL DaveInFL - 2 months ago 24
jQuery Question

jQuery Datepicker with Rails 4

I'm using jQuery Datepicker gem and when I'm editing a record that has a date it it behaves unexpectedly.

When I create a new record the date is entered with the mm/dd/yy format. When I go to edit the record the date is being populated in the date field in the format yyyy-dd-mm and I have no idea why. Perhaps this is something to do with Rails itself?

The Date column in the table is set to Date, which I would imagine is fine. Is there something that I need to do in my view when displaying the date or something in the controller?

This is what is in my application.js file:

$(document).on('page:change', function () {
$('#cust_dob').datepicker({
changeMonth: true,
changeYear: true,
dateFormat: "mm/dd/yy",
yearRange: "1900:+0"
});
});


Any help would be much appreciated.

Answer

Ok, I was able to get this working. There were two issues. The first is that the date wasn't always getting saved into the database table because of a difference of format. So, I used a hidden field and used the altFormat and altField options of the datapicker. The second issue was formatting a current date when editing a record. This was achieved using strftime as DevDue suggested. So, for those that are interested here is what I have in my view. Not saying this is the best way since I really am still learning RoR, but it works :)

So, my partial view with the date:

<div class="span2 input">
  <% dob_display = :dob %>
  <%= f.text_field dob_display,  placeholder: "mm/dd/yyyy", required: true, id: "cust_dob", value: @customer.dob.try(:strftime, "%m/%d/%Y") %>
  <%= f.hidden_field :dob, id: "cust_dobalt" %>
</div>

It took me a while to realise that unless the hidden_field comes after the visble field it just doesn't work!

My application.js file for this datepicker looks as follows. Notice the altField and altFormat:

$(document).on('page:change', function () {
    $('#cust_dob').datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: "mm/dd/yy",
        yearRange:  "1900:+0",
        altField:   "#cust_dobalt",
        altFormat:  "yy-mm-dd",
        duration:   "slow"
    });
});
Comments