Rails 3.1 text_field form helper and jQuery datepicker date format

前端 未结 4 870
死守一世寂寞
死守一世寂寞 2021-01-06 04:19

I have a form field in my Rails view like this:

<%= f.text_field :date, :class => \"datepicker\" %>

A javascript function converts

相关标签:
4条回答
  • 2021-01-06 04:19

    What I ended up doing is to just create a normal text input and prepopulate it with an ISO formatted date and additional information to mark it as a date input (say, rel="date").

    On the client side, I have JavaScript to create a new hidden input that takes on the name of the original field (thus overriding it, for good measure I also delete the name property of the original). The datepicker is attached to the original field, and uses altField/altFormat to sync the hidden field with an ISO date.

    // used in jQuery's .each
    function create_datepicker_for(_, el) {
      var e = $(el),
          mirror,
          date;
    
      // attach a hidden field that mirrors the proper date
      mirror = $('<input type="hidden"></input>')
               .prop('name', e.prop('name'))
               .insertAfter(e);
    
      if (e.val()) { date = new Date(e.val()); }
    
      e
      .prop('name', '')       /* make sure this is not sent to the application */
      .datepicker({
        altField: mirror,     /* "mirror" is the hidden field */
        altFormat: 'yy-mm-dd' /* you do not want anything but ISO */
      });
    
      if (date) { e.datepicker('setDate', date) }
    }
    

    This appears to keep everything in sync, sends the proper date format to the application, and degrades as well as anyone would expect it to.

    0 讨论(0)
  • 2021-01-06 04:26

    JQuery datepicker won't format the pre-populated date.
    You would need to handle it on the rails side by using the formatted date with the textfield, instead of the raw date which has the default 'yyyy-mm-dd' format.

    Example -

    <%= f.text_field :date, :class => "datepicker", :value => @model.date.strftime("%d %m %Y") %>
    

    More examples @ Rails date format in a text_field

    0 讨论(0)
  • 2021-01-06 04:42

    if your are using mysql database you can format the date in query itself.

    Sample code

         date_format(date_field,"%d %m %y")
    
    0 讨论(0)
  • 2021-01-06 04:45

    SOLVED: I pass in the :value => show.date as suggested by Jayendra above. The reason it wasn't working was because I didn't pass in the show object from the parent view. I changed the render line to include it - the parent view now looks like this:

    <%= form_tag("/shows/update_individual", :method => "put") do %>
        <% for show in @shows %>
            <%= fields_for "shows[]", show do |f| %>
                <%= render "fields", :f => f, :show => show %>
            <% end %>
        <% end %>
        <%= submit_tag "Submit"%>
    <% end %>
    
    0 讨论(0)
提交回复
热议问题