2014-03-28 46 views
1

我有以下形式的組最好的辦法:jQuery的 - 添加/刪除表格部分動態

<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中的代碼,但這似乎過於複雜。

回答

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> 
+0

謝謝,這工作對我來說就像魅力。 – user1049961