Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save TENorbert/aaf674cc0f5a3ef75b439e817614eed2 to your computer and use it in GitHub Desktop.
Save TENorbert/aaf674cc0f5a3ef75b439e817614eed2 to your computer and use it in GitHub Desktop.
This simple javascript anables you to dymanically create multiple objects (forms with datepicker). selector is the specific object you want to dynamically create, e.g for table rows <tr> call like so: cloneFormObject('.tr:last', 'gates');
function cloneFormObject(selector, prefix) {
var currentElement = $(selector)
var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());
$(currentElement).find('input.date_picker').datepicker({dateFormat:"M-dd-yy", minDate:0, autoclose:true});
var newElement = $(currentElement).clone(true).get(0);
$(newElement).removeAttr('id').insertAfter($(currentElement)).children('.hidden').removeClass('hidden');
$(newElement).find(':input').each(function() {
var name = $(this).attr('name').replace('-' + (formCount-1) + '-','-' + formCount + '-');
var id = 'id_' + name;
$(this).attr({'name': name, 'id': id}).val('').removeAttr('checked');
});
$(newElement).find('label').each(function() {
var newFor = $(this).attr('for').replace('-' + (formCount-1) + '-','-' + formCount + '-');
$(this).attr('for', newFor);
});
// MUST assigned new date picker at the end for new id!
$(newElement).find('input.date_picker').attr("id", "")
.removeClass('hasDatepicker').removeData('datepicker')
.unbind().datepicker({dateFormat:"M-dd-yy", minDate:0, autoclose:true});
$('#id_' + prefix + '-TOTAL_FORMS').val(formCount + 1);
return false;
}
@TENorbert
Copy link
Author

To clone say a formset with already made tools where you just want to add links for the client to click to either delete or create a formset_factory for example, use this: https://github.com/elo80ka/django-dynamic-formset/blob/master/docs/usage.rst

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment