I'm working on a Django project. But my problem is on JQuery. I used jquery.formset.js JQuery plugin to add form dynamically in inline_formsets, formset_factories. And this works pretty nice. It duplicates the first row elements with its other decoration tags (like div, span, img..) and adds the new row in the bottom of the table. So the duplicated row can be appeared just like the origin.
I also uses jquery ui (datepicker, autocomplete..etc) in my forms.
The duplication copies everything, even the appended htmls by the datepickers and autocompletes, because the plugin tries not to leave any interface pieces. When it clones the first row, everything is cloned, even the events are cloned. So when i click on the newly appeared datepicker input the calendar event works on the first row's element.
I'm trying to find the decision. Here are what in my mind so far..
Declare the jquery ui (datepicker and autocomplete) as live? like
$(".dates").live('...', function() { $(this).datepicker(); } )
But I'm not sure which event should be handled for this. I guess it's impossible to handle the new created or appended elements.
Putting the script inside the row? right after the element
$("#id_birthday_1").datepicker();It seems the best idea, but the duplication has already duplicated the extra elements/htmls. So it will re-render the element.
Should I edit the js plugin? like binding all the jquery ui's events' declarations, excepting the renders and appending and styling. That would be a huge mess. I don't want to mess up like this.. And every time if i need to add a new ui, i should edit that js constantly
Every ideas would be appreciated :)
Your first idea is a good one.
each
function:.
$(".dates").each(function (i) {
$(this).datepicker();
}
So basically, copy all the elements before you activate the datepicker on them. jQuery's each
allows you to activate a whole list of elements in one step.
Edit: If you need to generate new clones dynamically, you can store the row's HTML in a variable. When your user adds a row, you can do something like:
$(".date", $(rowHTML).appendTo($("#my-form-fields"))).datepicker();
which adds in a new row into the form, and then initializes that row's datepicker.
Edit2: and the above code is equivalent to
$(rowHTML).appendTo($("#my-form-fields")).find(".date").datepicker();
The formset plugin can call a function when a new form is added, you could initialize the newly added fields there. The function should take a single argument, row
; it will be passed a jQuery object, wrapping the form that was just added.
$('#myFormset1Table tbody tr').formset({
added: function(row) {
row.find(".date").datepicker();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With