重命名属性名称,如果一个属性在提交前被删除,使用jQuery


Renaming attributes names if one is deleted before submit with jQuery

我有一个jQuery生成的输入列表:

<input type='text' name='field["+ j++ +"]' />
<input type='file' name='field["+ j++ +"]' />
<textarea name='field["+ j++ +"]' value='' />
<textarea name='field["+ j++ +"]' value=''/>

j++在用户添加一个新的输入字段时增加,最后看起来像这样:

<input type='text' name='field[0]' />
<input type='file' name='field[1]' />
<textarea name='field[2]' value='' />
<textarea name='field[3]' value=''/>

现在用户可以用按钮删除字段,例如:如果我删除字段[2],结果如下:

<input type='text' name='field[0]' />
<input type='file' name='field[1]' />
<textarea name='field[3]' value=''/>

问题是,增量字段不再适合以后,因为不是像0,1,2,3…我有0,1,3…

我只是想更改已删除字段后的字段的number属性,以适应其他增量字段

另一件事:用户可以拖放字段来更改顺序。因此,如果1字段被删除后面的字段必须占其数字位置,等等

删除字段的代码:

$("#deletebtn").live("click", function(){
  $(this).parent("li").remove();
});

您可以省略索引,仅使用field[]

为所有元素添加一个通用的类名

<input type='text' name='field[0]' class='dynamic-order' />
<input type='file' name='field[1]' class='dynamic-order' />
<textarea name='field[2]' value='' class='dynamic-order' />
<textarea name='field[3]' value='' class='dynamic-order' />

删除元素后,遍历字段并设置新索引:

$("#deletebtn").live("click", function(){
  $(this).parent("li").remove();
  $( ".dynamic-order" ).each(
    function( index ) {
    this.name = "field["+index+"]";
    }
  );
});

编辑:我发现你的jsfiddle有一些问题,这是修复的版本:

http://jsfiddle.net/ZKFHH/1/

由于某些原因,名称并不总是显示最近的值,您必须检查它的属性

首先:如果你使用的名称形式张贴它与php(或asp)作为数组,你需要枚举输入的名称,你可以使用name="field[]"。

如果你只希望名字是这样的,那么给你的输入一个类:

<input type='text' class="input" name='field[0]' />
<input type='file' class="input" name='field[1]' />
<textarea class="input" name='field[2]' value='' />
<textarea class="input" name='field[3]' value=''/>

然后使用jquery,每次用户更改顺序或删除输入时,只需执行这个函数:

function re_order(class)
{
  $('.'+class).each(function(index,element){
    this.name='field['+index']';
  });
}

其中class为输入的类。