Rails 3 Nested Form - jQuery Datepicker won't load when “add a task”

坚强是说给别人听的谎言 提交于 2019-12-02 12:18:14

问题


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


回答1:


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"




回答2:


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(); 
}



回答3:


Put this at the top of your view:

= javascript_include_tag 'datepicker'


来源:https://stackoverflow.com/questions/8700248/rails-3-nested-form-jquery-datepicker-wont-load-when-add-a-task

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!