jquery - 使用 jQuery 克隆在表单输入字段的多维数组中递增键

标签 jquery

我正在尝试将这两个答案中的信息拼凑在一起,但这似乎都没有以我可以推断并开始针对我的情况工作的方式涵盖该问题。所以,如果这看起来像是重复的,请不要惩罚我;我认为不是。

Increment multidimensional array when form fields are cloned

Copy table row and increment all name attributes

<tr>
    <td><input type="text" name="pricing['prices'][0]['label']" value="" /></td>
    <td><input type="text" name="pricing['prices'][0]['price']" value="" /></td>
    <td><input type="text" name="pricing['prices'][0]['expires']" value="" /></td>
    <td><input type="text" name="pricing['prices'][0]['bulk-price']" value="" /></td>
    <td><input type="text" name="pricing['prices'][0]['bulk-qty']" value="" /></td>
</tr>

是我尝试使用此按钮克隆的内容:

<input type="button" id="newRowButton" value="Add Another Price" />

脚本(到目前为止,克隆有效,但它不会将“0”更改为“1”。我显然错过了一些我无法通过将其他两个答案中的示例拼凑在一起来弄清楚的东西)

$("#newRowButton").live('click',function(e) {
    e.preventDefault();
  $("table.tablearray tr:last")
      .clone()
      .find(':input')
      .each(function(){
            this.name = this.name.replace(/\[(\d+)\]$/,
                                          function(str,p1){
                                              return '[' + (parseInt(p1,10)+1) + ']';
                                          });
        })
    .end()
    .appendTo("table")
});

如有任何帮助,我们将不胜感激。理想情况下,我还想添加一个“删除行”按钮。

最佳答案

从正则表达式中取出 $ 符号,如下所示:

$("#newRowButton").live('click',function(e) {
    e.preventDefault();
  $("table.tablearray tr:last")
      .clone()
      .find(':input')
      .each(function(){
            this.name = this.name.replace(/\[(\d+)\]/, function(str,p1){
                return '[' + (parseInt(p1,10)+1) + ']';
            });
        })
    .end()
    .appendTo("table")
});

$ 强制它在名称末尾查找 [0],而这不是您所拥有的。

这里的工作演示:http://jsfiddle.net/jfriend00/S9Q8W/

关于jquery - 使用 jQuery 克隆在表单输入字段的多维数组中递增键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8609667/

相关文章:

jquery - 使用 jQuery.ajax() 保存匿名 github 要点

php - 在 JQuery 中调用/获取 php 变量值

javascript - jQuery - 顺序运行多个方法

javascript - 将运行时参数值发送到 jQuery 的 ON 方法?

javascript - 在 jQuery .html 中使用 javascript var

javascript - 带有第三方主题模板的 Ember.js

jQuery - 选择具有特定样式的子项

jquery - 在 Jquery Image Slider 的初始页面加载时隐藏特定图像

javascript - Ajax 不工作。我需要页眉和页脚不要每次都重新加载。你能帮助我吗?

javascript - 更改选定链接的颜色