Повторение div с полями формы
У меня есть форма, где я хочу иметь возможность дублировать группу полей столько раз, сколько я хочу. И я тоже хочу иметь поле id
, name
и лейбл for
атрибуты этой новой группы полей увеличиваются на 1. Я пробовал это до сих пор с jQuery, и получил, по крайней мере, дублировать группу полей, но удалить не работает. И я не уверен, как сделать +1 для каждого из этих 3 атрибутов. Я ценю любую помощь, которую я могу получить.
Вот его jsfiddle, http://jsfiddle.net/Unfxn/
HTML
<form method="post" action="#" class="inlineForm" enctype="multipart/form-data">
<div class="repeatingSection">
<a href="#" class="buttonGray buttonRight deleteFight">Delete</a>
<input type="hidden" name="fighter_a_id_1" id="fighter_a_id_1" value="" />
<input type="hidden" name="fighter_b_id_1" id="fighter_b_id_1" value="" />
<input type="hidden" name="winner_id_1" id="winner_id_1" value="" />
<div class="formRow">
<label for="fighter_a_1">Fighters</label>
<input type="text" name="fighter_a_1" id="fighter_a_1" value="" /> <span class="formTextExtraCenter">vs</span> <input type="text" name="fighter_b_1" id="fighter_b_1" value="" />
</div>
<div class="formRow">
<label for="fighter_a_pay_1">Fighter Pay $</label>
<input type="text" name="fighter_a_pay_1" id="fighter_a_pay_1" value="" /> <span class="formTextExtraCenter">vs</span> <input type="text" name="fighter_b_pay_1" id="fighter_b_pay_1" value="" />
</div>
<div class="formRow">
<label for="winner_1">Winner</label>
<input type="text" name="winner_1" id="winner_1" value="" />
</div>
<div class="formRow">
<label for="method_1">Method</label>
<input type="text" name="method_1" id="method_1" value="" />
</div>
<div class="formRow">
<label for="method_type_1">Method Type</label>
<input type="text" name="method_type_1" id="method_type_1" value="" />
</div>
<div class="formRow">
<label for="round_1">Round</label>
<input type="text" name="round_1" id="round_1" class="fieldSmall" value="" />
</div>
<div class="formRow">
<label for="time_1">Time</label>
<input type="text" name="time_1" id="time_1" class="fieldSmall" value="" />
</div>
<div class="formRow">
<label for="fight_number_1">Fight #</label>
<input type="text" name="fight_number_1" id="fight_number_1" class="fieldSmall" value="" />
</div>
</div>
<div class="formRowRepeatingSection">
<a href="#" class="buttonGray buttonRight addFight">Add Fight</a>
</div>
<div class="formRow">
<input type="submit" class="submitButton" value="Save Fights" />
</div>
</form>
JS
// Add a new repeating section
$('.addFight').click(function(){
var lastRepeatingGroup = $('.repeatingSection').last();
lastRepeatingGroup.clone().insertAfter(lastRepeatingGroup);
return false;
});
// Delete a repeating section
$('.deleteFight').click(function(){
$(this).parent('div').remove();
return false;
});
4 ответа
Это должно автоматически переименовать все три элемента:
// Add a new repeating section
$('.addFight').click(function(){
var currentCount = $('.repeatingSection').length;
var newCount = currentCount+1;
var lastRepeatingGroup = $('.repeatingSection').last();
var newSection = lastRepeatingGroup.clone();
newSection.insertAfter(lastRepeatingGroup);
newSection.find("input").each(function (index, input) {
input.id = input.id.replace("_" + currentCount, "_" + newCount);
input.name = input.name.replace("_" + currentCount, "_" + newCount);
});
newSection.find("label").each(function (index, label) {
var l = $(label);
l.attr('for', l.attr('for').replace("_" + currentCount, "_" + newCount));
});
return false;
});
// Delete a repeating section
$('.deleteFight').live('click',function(){
$(this).parent('div').remove();
return false;
});
Я изменил обработчик удаления, чтобы использовать вместо него .live(), чтобы обработчик также прикреплялся к вновь созданным копиям этой кнопки. Теперь, если вы используете jquery > 1.7, вы должны использовать .on()
Версия on () будет выглядеть так:
// Delete a repeating section
$(document).on('click','.deleteFight',function(){
$(this).parent('div').remove();
return false;
});
Используйте это после клонирования вашего объекта
Возиться:):) http://jsfiddle.net/fedmich/MZjKR/1/
Я оставлю немного TODO для вас, замените 3 на текущее число id
<script type="text/javascript">
$.fn.id_changer = function(new_id) {
return this.each(function(){
$(this).find('input').each(function(){
var ob = $(this);
ob.attr('id', this.id.replace(/_\d$/, '_' + new_id));
ob.attr('name', this.name.replace(/_\d$/, '_' + new_id));
});
});
};
Вот моя версия.
Он сильно зависит от индекса повторяющейся области. Так что не добавляйте братьев и сестер над ним. Если вам это нужно, то оберните все повторяющиеся области в другой div.
Черт! слишком поздно:) в любом случае... вот код.
// 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));
})
})
});
Если вы используете
name=method[]
и т. д. в качестве полей, вы получите массивы в переменной POST, поэтому вам не нужно явное индексирование.