我要在表单中实现“添加新行”功能.表单的结构类似于:
- <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>
如图所示,对于每一行,v []的数量都会增加. v1,v2 ……依此类推
我在寻找什么
单击“添加一行”按钮时,应执行以下操作
>在最后一行(带有的行)上方插入一个新行
纽扣)
> name属性值增加1(即v2 [label]变为
v3 [标签],v2 [观察]变成v3 [观察]等等
行
我做了什么
我最接近的是使用jQuery的clone().这确实完美地添加了行.但是我发现很难找到一种方法,每次单击按钮时都会将name属性的值增加1.
当下正在使用的jquERY
- $('input:button[id="addrow"]').click(function(){
- var secondlast = $('table tr:last').prev('tr');
- secondlast.clone().insertBefore(secondlast);
- });
如果我单击按钮两次,我将添加以下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>
因此添加了一行,但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);
- });
编辑
- // you could also simply increment any digit you find as Batman indicated
- var newNameAttr = currentNameAttr.replace(/\d+/,function(match) {
- return (parseInt(match)+1);
- });