Rails 3 Nested Form - jQuery Datepicker won't

2019-03-01 06:28发布

I'm using ryan bates nested form gem. - https://github.com/ryanb/nested_form

In nested form I have a textfield for jQuery datepicker.

My Problem is when I "Add a task". The datepicker no respond.

FYI - In my controller I generate 3.times for the nested form. All the 3 generated nested form, the datepicker work. Just when I add new or (delete and re-add), it wont work. - my jQuery datepicker script is in application.js

3条回答
三岁会撩人
2楼-- · 2019-03-01 07:06

Looks old, but I'm posting mostly for my own sake.

If you use the code from the ryan Bates rails casts then you already have the helper. I didn't change that. I did however convert from coffeescript to javascript. I did this because I was getting a strange conflict that was needed to be cleared out. I also made a few additions.

Important: for this implementation, you have to add a class of datepicker.

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

I made a asset javascript file for this script and it works across the site once required into the application.js file.

$(document).ready(function() {
  var $j = jQuery.noConflict();

  /* Set each input item with class of datepicker to a datepicker */
  $("input.datepicker").each(function(){
    $(this).datepicker({
      dateFormat: 'yy-mm-dd',
      autoSize: true
    });
  });

  var datepicker_update = function() {
    return $("input.datepicker").datepicker({
      dateFormat: 'yy-mm-dd',
      autoSize: true
    });
  };

  $('form').on('click', '.remove_fields', function(event) {
      $(this).prev('input[type=hidden]').val('1');
      $(this).closest('fieldset').hide();
      return event.preventDefault();
    });

  $('form').on('click', '.add_fields', function(event) {
    var regexp,time;
    time = new Date().getTime();
    regexp = new RegExp($(this).data('id'), 'g');
    $(this).before($(this).data('fields').replace(regexp, time));
    event.preventDefault();
    return datepicker_update();
  });
});

Hope this helps

Thanks to the post at Adding a date picker to a nested form field & JQuery UI datepicker within rails nested forms & Rails 3 Nested Form - jQuery Datepicker won't load when "add a task"

查看更多
3楼-- · 2019-03-01 07:08

Put this at the top of your view:

= javascript_include_tag 'datepicker'
查看更多
Emotional °昔
4楼-- · 2019-03-01 07:13

try adding the datepicker pluging after the row creation too :

it would look like this (the function names and class names will be different of course)

function addTask()
{
   ......
   ......
   $("textfield-slector").datepicker(); 
}
查看更多
登录 后发表回答