我有一个带有选择元素的表单,我想通过选择添加和删除其中的一些元素。这是html代码(也有jsfiddle在这里http://jsfiddle.net/txhajy2w/):
<form id="Form" action="#" method="POST">
<div id="FormContainer">
<div class="Row" id="container_0">
<a id="delete_link_0">
<i class="glyphicon glyphicon-minus"></i>
</a>
<select class="type_name" name="type_name_0" id="type_name_0">
<option value="">Select an Option</option>
<optgroup label="All Options">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</optgroup>
</select>
<a id="new_link_0">
<i class="glyphicon glyphicon-plus"></i>
</a>
</div>
</div>
<div>
<input type="submit" name="submit" value="Submit">
</div>
</form>
我需要的是:
- 点击加号将生成一个新行(包括一个div, select和加减号链接)。但是,对于新行,我需要为元素添加新的id和名称(使用数字,例如type_name_1、type_name_2等,仅更改索引号)。
- 单击减号,将删除该特定行,并重新编号所有剩余元素的id。
Ok再次添加select
元素并添加新ID,并删除最后添加的select元素,您可以执行以下操作:
演示strong>
$('#new_link_0').on('click',function(){
var select=$('.wrap').find('select:last').clone();
var id=$(select).attr('id').split('_')[2];
$(select).attr('id','type_name_'+parseInt(id+1));
$(select).attr('name','type_name_'+parseInt(id+1));
$(select).insertAfter('.wrap select:last');
});
$('#delete_link_0').on('click',function(){
$('.wrap').find('select:last').remove();
});
更新strong>
要每次添加一个新项目并将整套ids
重置为正确的计数,您可以按如下操作,但您需要遵循以下html
结构:
演示strong>