我要在表单中实现"添加新行"功能.表单的结构类似于:
<table>
<tr>
<td><input type="text" name="v1[label]" /></td>
<td><input type="text" name="v1[observation]" /></td>
<td><input type="text" name="v1[remarks]" /></td>
</tr>
<tr>
<td><input type="text" name="v2[label]" /></td>
<td><input type="text" name="v2[observation]" /></td>
<td><input type="text" name="v2[remarks]" /></td>
</tr>
<tr>
<td colspan="3">
<input type="button" id="addrow" value="Add One More Row">
<input type="submit" name="proceed" value="Submit" />
</td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
如图所示,每行都有v[]数量增加.v1,v2 ......依此类推
我在寻找什么
单击"添加一行"按钮时,应执行以下操作
我做了什么
我最接近的是使用jQuery's clone().这确实完美地添加了行.但是我发现很难找到一种方法,每次单击按钮时都会将name属性的值增加1.
当下正在使用的jquERY
$('input:button[id="addrow"]').click(function(){
var secondlast = $('table tr:last').prev('tr');
secondlast.clone().insertBefore(secondlast);
});
Run Code Online (Sandbox Code Playgroud)
如果我单击该按钮两次,我将添加以下HTML
<tr>
<td><input type="text" name="v2[label]" /></td>
<td><input type="text" name="v2[observation]" /></td>
<td><input type="text" name="v2[remarks]" /></td>
</tr>
<tr>
<td><input type="text" name="v2[label]" /></td>
<td><input type="text" name="v2[observation]" /></td>
<td><input type="text" name="v2[remarks]" /></td>
</tr>
Run Code Online (Sandbox Code Playgroud)
因此添加了一行,但name属性保留在v2,而第三和第四行应该是v3和v4.我明白clone()不能这样做,这就是为什么我在寻找替代方案.
$('input:button[id="addrow"]').click(function(){
var secondlast = $('table tr:last').prev('tr');
var newClone = secondlast.clone();
// find all the inputs within your new clone and for each one of those
newClone.find('input').each(function() {
var currentNameAttr = $(this).attr('name'); // get the current name attribute
// construct a new name attribute using regular expressions
// the match is divided into three groups (indicated by parentheses)
// p1 will be 'v', p2 will be the number, p3 will be the remainder of the string
var newNameAttr = currentNameAttr.replace(/^(v)(\d+)(.*)$/, function(match, p1, p2, p3) {
return p1+(parseInt(p2)+1)+p3;
});
$(this).attr('name', newNameAttr); // set the incremented name attribute
});
// insert after is I assume what you want
newClone.insertAfter(secondlast);
});
Run Code Online (Sandbox Code Playgroud)
编辑
// you could also simply increment any digit you find as Batman indicated
var newNameAttr = currentNameAttr.replace(/\d+/, function(match) {
return (parseInt(match)+1);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2707 次 |
| 最近记录: |