我有以下表单组:
<div id="edu_row1">
<div class="form-group">
<label class="sr-only" for="edu_row_1_name"><?php _e('Name','ja'); ?></label>
<input type="text" class="form-control" name="edu_row[1][name]" value="<?php echo $edu_item['name']; ?>" id="edu_row_[1]_name" placeholder="<?php _e('Enter school name','ja'); ?>">
</div>
<div class="form-group">
<label class="sr-only" for="edu_row_from_date_1"><?php _e('From date','ja'); ?></label>
<input type="text" class="form-control" value="<?php echo $edu_item['from_date']; ?>" id="edu_row_date_1_from" name="edu_row[1][from]" placeholder="<?php _e('From date','ja'); ?>">
</div>
<div class="form-group">
<label class="sr-only" for="edu_row_to_date_1"><?php _e('To date','ja'); ?></label>
<input type="text" class="form-control" value="<?php echo $edu_item['to_date']; ?>" id="edu_row_date_1_to" name="edu_row[1][to]" placeholder="<?php _e('To date','ja'); ?>">
</div>
<input type="text" class="form-control" value="1" id="edu_row_<?php echo $i; ?>_id" name="edu_row[1][id]" placeholder="<?php _e('ID','ja'); ?>">
</div>
使用适当的索引添加/删除按钮以添加jQuery的另一个部分的最佳方法是什么?我尝试使用http://bootsnipp.com/snippets/featured/dynamic-form-fields-add-amp-remove中的代码,但这似乎太过复杂了。
答案 0 :(得分:1)
var clone = $('#edu_row1').clone(),
number = $('.edu_row').length+1;
//add new id to the clone
clone.attr('id', 'edu_row'+number)
//change label
.find('label').each(function(){
$(this).attr('for', $(this).attr('for').replace('_1_', '_'+number+'_'));
});
//change inputs inside the form-group
clone.find('.form-group > input').each(function(){
$(this).attr('id', $(this).attr('id').replace('_1_', '_'+number+'_'));
$(this).attr('name', $(this).attr('id').replace('[1]', '['+number+']'));
});
//change latest input
clone.find('input.form-control').last().each(function(){
$(this).attr('id', $(this).attr('id').replace('_1', '_'+number+''));
$(this).attr('name', $(this).attr('id').replace('[1]', '['+number+']'));
$(this).val(number);
});
//insert the clone after the last
clone.insertAfter('.edu_row:last');
这需要额外的课程:
<div id="edu_row1" class="edu_row">
...
</div>