Rails render form + jQuery problem
I have a little mistake about jQuery with a render form.
I have link_to_add_fields to add nested render. The problem is when i add field, my jQuery stop working. I have no error, nothing just my jquery stop working.
Here is my code from helper and jquery
def link_to_remove_fields(name, f)
f.h开发者_如何学Goidden_field(:_destroy) + link_to_function(name, "remove_fields(this)")
end
def link_to_add_fields(name, f, association)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
render(association.to_s.singularize + "_fields", :f => builder)
end
link_to_function(name, ("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"))
end
function add_fields(link, association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g")
$(link).parent().before(content.replace(regexp, new_id));
}
The jquery i try to use is the datepicker from jQuery UI. my render :
<div class="field">
<div>
<%= f.label :work_start_date %><br/>
<%= f.text_field :work_start_date, :class => 'calpicker' %>
</div>
<div>
<%= f.label :work_end_date %><br/>
<%= f.text_field :work_end_date, :class => 'calpicker' %>
</div>
<div>
<%= f.label :value_renovation %><br/>
<%= f.text_field :value_renovation %>
</div>
<div>
<%= f.label :note %><br/>
<%= f.text_area :note, :rows => '3' %>
</div>
</div>
and my script for the class calpicker
jQuery(function() {
// for PikaChoose
$(".calpicker").datepicker();
});
i see a difference between my nested render after a link_to_add_field and if i set defaut view from my controller (mymodel.nestedmodel.build)
with mymodel.nestedmodel.build my class have 'hasDatepicker' with my calpicker, with my render i dont have this element in my class.
What can i do? with my firebug i see no error.
Thanks for your help.
You are having this problem because you are adding fields after the DOM has loaded and after $(".calpicker").datepicker();
has run so the new fields are not included to have a datepicker.
You will need to use the .live function to achieve this functionality so have a look at this article it might help: http://www.vancelucas.com/blog/jquery-ui-datepicker-with-ajax-and-livequery/
Extracted and modified source:
jQuery(function() {
$('input.calpicker').live('click', function() {
$(this).datepicker({showOn:'focus'}).focus();
});
});
精彩评论