【发布时间】:2014-08-19 08:32:32
【问题描述】:
我有一个带有重复部分的表格。为了创建重复部分,我使用了这段代码的一个轻微变体:
// Add a new repeating section
var attrs = ['for', 'id', 'name'];
function resetAttributeNames(section) {
var tags = section.find('input, label'), idx = section.index();
tags.each(function() {
var $this = $(this);
$.each(attrs, function(i, attr) {
var attr_val = $this.attr(attr);
if (attr_val) {
$this.attr(attr, attr_val.replace(/_\d+$/, '_'+(idx + 1)))
}
})
})
}
$('.addFight').click(function(e){
e.preventDefault();
var lastRepeatingGroup = $('.repeatingSection').last();
var cloned = lastRepeatingGroup.clone(true)
cloned.insertAfter(lastRepeatingGroup);
resetAttributeNames(cloned)
});
// Delete a repeating section
$('.deleteFight').click(function(e){
e.preventDefault();
var current_fight = $(this).parent('div');
var other_fights = current_fight.siblings('.repeatingSection');
if (other_fights.length === 0) {
alert("You should atleast have one fight");
return;
}
current_fight.slideUp('slow', function() {
current_fight.remove();
// reset fight indexes
other_fights.each(function() {
resetAttributeNames($(this));
})
})
});
JSF 搞砸了 - http://jsfiddle.net/Unfxn/27/
我最初从这个线程中找到了代码: Repeating div with form fields
但是,这段代码有一个问题:如果你填写表单域,然后点击“添加战斗”,新的重复部分不仅复制了表单域,还复制了它们的值。我想我需要使用这样的东西来清除新表单部分的值:
$(this).closest('form').find("input[type=text], textarea").val("");
但我不确定如何将其整合到我已有的功能中。那么,一旦创建了新的表单部分,如何清除字段的值呢?
【问题讨论】:
标签: javascript jquery forms repeat