Rails 3.1 text_field form helper and jQuery datepicker date format

前端 未结 4 883
死守一世寂寞
死守一世寂寞 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 = $('')
               .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.

提交回复
热议问题