Last active
December 14, 2018 17:56
-
-
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');
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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