我正在运行一个在GITHUB中找到的表单集脚本的修改版本。
;(function($) {
$.fn.formset = function(opts)
{
var options = $.extend({}, $.fn.formset.defaults, opts),
flatExtraClasses = options.extraClasses.join(' '),
totalForms = $('#id_' + options.prefix + '-TOTAL_FORMS'),
initialForms = $('#id_' + options.prefix + '-INITIAL_FORMS'),
currentFormIndex = parseInt(totalForms.val()),
maxForms = $('#id_' + options.prefix + '-MAX_NUM_FORMS'),
minForms = $('#id_' + options.prefix + '-MIN_NUM_FORMS'),
childElementSelector = 'input,select,textarea,label,div',
$$ = $(this),
applyExtraClasses = function(row, ndx) {
if (options.extraClasses) {
row.removeClass(flatExtraClasses);
row.addClass(options.extraClasses[ndx % options.extraClasses.length]);
}
},
updateElementIndex = function(elem, prefix, ndx) {
var idRegex = new RegExp(prefix + '-(\\d+|__prefix__)-'),
replacement = prefix + '-' + ndx + '-';
if (elem.attr("for")) elem.attr("for", elem.attr("for").replace(idRegex, replacement));
if (elem.attr('id')) elem.attr('id', elem.attr('id').replace(idRegex, replacement));
if (elem.attr('name')) elem.attr('name', elem.attr('name').replace(idRegex, replacement));
},
hasChildElements = function(row) {
return row.find(childElementSelector).length > 0;
},
showAddButton = function() {
return maxForms.length == 0 ||
(maxForms.val() == '' || (maxForms.val() - totalForms.val() > 0));
},
showDeleteLinks = function() {
return minForms.length == 0 ||
(minForms.val() == '' || (totalForms.val() - minForms.val() > 0));
},
insertDeleteLink = function(row) {
var delCssSelector = $.trim(options.deleteCssClass).replace(/\s+/g, '.'),
addCssSelector = $.trim(options.addCssClass).replace(/\s+/g, '.');
var delButtonHTML = document.createElement("a");
delButtonHTML.classList.add(options.deleteCssClass);
delButtonHTML.textContent = options.deleteText;
delButtonHTML.id = "deleteID";
if (options.deleteContainerClass) {
row.find('[class*="' + options.deleteContainerClass + '"]').append(delButtonHTML);
} else if (row.is('TR')) {
row.children(':last').append(delButtonHTML);
} else if (row.is('UL') || row.is('OL')) {
row.append('<li>' + delButtonHTML + '</li>');
} else {
row.append(delButtonHTML);
}
if (!showDeleteLinks()){
row.find('a.' + delCssSelector).hide();
}
row.find('a.' + delCssSelector).click(function() {
var result = confirm("Are you sure you want to Delete3?");
if (result) {
var row = $(this).parents('.dynamic-form');
var itemIdInput = row.find('input:hidden[id $= "-id"]');
var itemId = itemIdInput.val();
var deleteInput = `<input type="hidden" name="line_items_to_delete" value="${itemId}">`; // Update here....
if( $(deleteInput).val() ) {
$('#line_items_to_delete').append(deleteInput); // Update here....
}
var row = $(this).parents('.' + options.formCssClass),
del = row.find('input:hidden[id $= "-DELETE"]'),
buttonRow = row.siblings("a." + addCssSelector + ', .' + options.formCssClass + '-add'),
forms;
if (del.length) {
del.val('on');
row.hide();
forms = $('.' + options.formCssClass);
totalForms.val(forms.length);
} else {
row.remove();
forms = $('.' + options.formCssClass).not('.formset-custom-template');
totalForms.val(forms.length);
}
for (var i=0, formCount=forms.length; i<formCount; i++) {
applyExtraClasses(forms.eq(i), i);
if (!del.length) {
forms.eq(i).find(childElementSelector).each(function() {
updateElementIndex($(this), options.prefix, i);
});
}
}
if (!showDeleteLinks()){
$('a.' + delCssSelector).each(function(){$(this).hide();});
}
if (buttonRow.is(':hidden') && showAddButton()) buttonRow.show();
if (options.removed) options.removed(row);
return false;
}
});
};
$$.each(function(i) {
var row = $(this),
del = row.find('input:checkbox[id $= "-DELETE"]');
if (del.length) {
if (del.is(':checked')) {
del.before('<input type="hidden" name="' + del.attr('name') +'" id="' + del.attr('id') +'" value="on" />');
row.hide();
} else {
del.before('<input type="hidden" name="' + del.attr('name') +'" id="' + del.attr('id') +'" />');
}
$('label[for="' + del.attr('id') + '"]').hide();
del.remove();
}
if (hasChildElements(row)) {
row.addClass(options.formCssClass);
if (row.is(':visible')) {
insertDeleteLink(row);
applyExtraClasses(row, i);
}
}
});
if ($$.length) {
var hideAddButton = !showAddButton(),
addButton, template;
if (options.formTemplate) {
template = (options.formTemplate instanceof $) ? options.formTemplate : $(options.formTemplate);
template.removeAttr('id').addClass(options.formCssClass + ' formset-custom-template');
template.find(childElementSelector).each(function() {
updateElementIndex($(this), options.prefix, '__prefix__');
});
insertDeleteLink(template);
} else {
if (options.hideLastAddForm) $('.' + options.formCssClass + ':last').hide();
template = $('.' + options.formCssClass + ':last').clone(true).removeAttr('id');
template.find('input:hidden[id $= "-DELETE"]').remove();
template.find(childElementSelector).not(options.keepFieldValues).each(function() {
var elem = $(this);
if (elem.is('input:checkbox') || elem.is('input:radio')) {
elem.attr('checked', false);
}
if (elem.is('select')) {
elem.append('<option style="display:none" selected value="">Optional</option>');
}
else {
elem.val('');
}
});
}
options.formTemplate = template;
var addButtonHTML = '<a class="' + options.addCssClass + '" href="javascript:void(0)">' + options.addText + '</a>';
if (options.addContainerClass) {
var addContainer = $('[class*="' + options.addContainerClass + '"');
addContainer.append(addButtonHTML);
addButton = addContainer.find('[class="' + options.addCssClass + '"]');
} else if ($$.is('TR')) {
var numCols = $$.eq(0).children().length,
buttonRow = $('<tr><td colspan="' + numCols + '">' + addButtonHTML + '</tr>').addClass(options.formCssClass + '-add');
$$.parent().append(buttonRow);
addButton = buttonRow.find('a');
} else {
$$.filter(':last').after(addButtonHTML);
addButton = $$.filter(':last').next();
}
if (hideAddButton) addButton.hide();
addButton.click(function() {
var formCount = currentFormIndex,
row = options.formTemplate.clone(true).removeClass('formset-custom-template'),
buttonRow = $($(this).parents('tr.' + options.formCssClass + '-add').get(0) || this),
delCssSelector = $.trim(options.deleteCssClass).replace(/\s+/g, '.');
let highestId = 0;
const idRegex = /\d+/;
$("input[name$='-research_line_item_description']").each(function(){ // Update here....
const currentName = $(this).attr('name');
const idVal = currentName.match(idRegex);
const idInt = parseInt(idVal);
highestId = Math.max(highestId,parseInt(idInt));
});
formCount = highestId+1;
applyExtraClasses(row, formCount);
row.insertBefore(buttonRow).show();
row.find(childElementSelector).each(function() {
updateElementIndex($(this), options.prefix, formCount);
});
totalForms.val(formCount + 1);
if (showDeleteLinks()){
$('a.' + delCssSelector).each(function(){$(this).show();});
RemoveFirstButton();
UpdatePlaceHolder();
UpdateTotals();
}
if (!showAddButton()) buttonRow.hide();
if (options.added) options.added(row);
currentFormIndex++;
return false;
});
}
return $$;
};
/* Setup plugin defaults */
$.fn.formset.defaults = {
prefix: 'form', // The form prefix for your django formset
formTemplate: null, // The jQuery selection cloned to generate new form instances
addText: 'Add', // Text for the add link
deleteText: 'Del', // Text for the delete link
addContainerClass: null, // Container CSS class for the add link
deleteContainerClass: null, // Container CSS class for the delete link
addCssClass: 'add-row-budget', // CSS class applied to the add link
deleteCssClass: 'delete-row-budget', // CSS class applied to the delete link
formCssClass: 'dynamic-form', // CSS class applied to each form in a formset
extraClasses: [], // Additional CSS classes, which will be applied to each form in turn
keepFieldValues: '', // jQuery selector for fields whose values should be kept when the form is cloned
added: null, // Function called each time a new form is added
removed: null, // Function called each time a form is deleted
hideLastAddForm: false, // When set to true, hide last empty add form (becomes visible when clicking on add button)
};
})(jQuery);
效果很好!有一个例外....我在检测按钮何时被点击时遇到了麻烦...如果我做下面的事情...
$(".add-row-budget").on('click', function() {
$(window).on('beforeunload',function(){
return '';
});
console.log("test1");
});
这不管用我有点明白为什么...元素是动态加载的...从我收集的信息来看...它们没有被绑定...或者我缺少一个Add-Event-Listener?我把这个加进去了
RemoveFirstButton();
UpdatePlaceHolder();
UpdateTotals();
这得到了“唤醒”的代码,在第一次通过后,我可以得到...
$(".add-row-budget").on('click', function() {
$(window).on('beforeunload',function(){
return '';
});
console.log("test1");
});
我怎样才能让上面的代码以一种不那么古怪的方式与原始代码协同工作呢?
提前感谢任何想法。
1条答案
按热度按时间sqyvllje1#
在我的HTML中…
我不得不包含几个UpdateFormset()引用,但这个解决方案最终成功了。