2011-10-16 26 views
0

提交我的的jQuery產生的輸入列表重命名的屬性名稱如果一個之前被刪除的jQuery

<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 ...

我只是想更改另一件事:用戶可以通過拖拽字段來改變順序。字段的數字屬性已被刪除以適應其他字段的遞增字段。

另一件事:用戶可以通過拖放字段來更改順序。所以如果1場被刪除後場右側一定要以數位等

的代碼刪除字段:

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

任何幫助將是非常讚賞。

回答

0

添加一個共同的類名的所有元素使用順序:

<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/

由於某些原因,名稱並不總是顯示最近的值,您必須檢查屬性。

+0

感謝您的回答!我試過,如果我刪除一個字段的索引不會改變,例如:我點擊刪除字段[2],其他人不改變他們的索引。任何想法? – user990463

+0

不知道,除非你鏈接到它使用的頁面:) – Esailija

+0

對不起,它是本地的:/也許這是因爲輸入是由jQuery生成 – user990463

1

您可以省略指數,使用所有的只有field[]

+0

感謝您的回答,我不能刪除索引,因爲我需要它在我的代碼後 – user990463

+0

這是什麼原因,它不看起來像索引和字段之間有特殊關​​系,只要你喜歡重新分配指數。 –

+0

是的,這是因爲在提交後我做了一些PHP操作來建立排名數組和輸入之間的關係,所以輸入必須有一個索引來匹配排名 – user990463

0

首先:如果您在使用該名稱的形式與PHP(或ASP)的陣列張貼你需要enumarete的輸入名字,你只能使用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是輸入的類。

+0

class是未來保留的關鍵字,只是指出:P https://developer.mozilla.org/en/JavaScript/Reference/Reserved_Words#section_1 – Esailija

+0

這打破了代碼:/ – user990463

相關問題