2012-04-04 40 views
0

我有一個表單,我需要動態地添加儘可能多的文本字段作爲用戶想要的。我希望文本字段是一個數組,例如:如何動態添加一個HTML數組元素[]

<input type="text" name="room_text[]"> 

我已經構建了一些我認爲會工作的東西。它成功添加了更多文本框。我增加了兩個文本框使用JavaScript動態,使得外觀形式是這樣的:

<input type="text" name="room_text[]"> 
     <input type="text" name="room_text[]"> 
     <input type="text" name="room_text[]"> 

但是,當我張貼到PHP文件,它只是變得第一個值。之所以我知道這是一個JavaScript問題,是因爲它可以正常工作,如果您在頁面加載時有多個文本框。它只是當你添加更多的文本框與JavaScript。

如果這會有所幫助,這是jQuery的功能,我用添加框:

$('.add').live("click", function() { 
    var mu = $(this).parent('td').parent('tr'); 
    var clone = $(this).parent('td').parent('tr').clone(); 
    $(clone).children('td').children('.add').remove(); 
    $(clone).children('td').children('.redtext').remove(); 
    $(clone).children('td').children('.remove').css("display", "inline"); 
    $(clone).css("display", "none"); 
    $(mu).after(clone); 
    $(clone).show("fast"); 
}); 
+1

您應該檢查的HTTP事務的樣子。在發佈表單時,您可以使用[插入數據](http://goo.gl/1AES9)等Firefox插件查看傳出HTTP請求的確切狀態。如果輸入元素顯示在頁面上,那麼這很可能不是JavaScript問題。 – Pointy 2012-04-04 14:01:10

+2

請確保輸入'room_text []'的名稱屬性設置正確......如果它們全都相同,那麼您將遇到提及的行爲 – xandercoded 2012-04-04 14:03:17

+0

您是否可以避免PHP參數array-name'[]'一起處理?也許在表單外部輸入文本,然後在提交時收集它們的值,將它們的值整理成隱藏的輸入(在表單內)並將其發佈到服務器。 – 2012-04-04 14:06:42

回答

1

我相信這個問題存在於.clone()功能。你可以嘗試不同的方法,比方說......

$('.add').live("click", function() { 
    var mu = $(this).parent('td').parent('tr'); 
    var clone = '<tr>' + $(this).parent('td').parent('tr').html() + '</tr>'; 
    $(clone).children('td').children('.add').remove(); 
    $(clone).children('td').children('.redtext').remove(); 
    $(clone).children('td').children('.remove').css("display", "inline"); 
    $(clone).css("display", "none"); 
    $(mu).after(clone); 
    $(clone).show("fast"); 
}); 

修訂 - 哎呀。在該版本中「克隆」是一個字符串,而不是元素,所以.children()功能不能正常工作......這裏有一個修正版本:

$('.add').live("click", function() { 
    var mu = $(this).parent('td').parent('tr'); 
    var clone = $('<tr>' + $(mu).html() + '</tr>'); 
    $(clone).children('td').children('.add').remove(); 
    $(clone).children('td').children('.redtext').remove(); 
    $(clone).children('td').children('.remove').css("display", "inline"); 
    $(clone).hide(); 
    $(mu).after(clone); 
    $(clone).show("fast"); 
});​ 
+0

我認爲,舊版本的IE和'.clone()'有一些已知問題......關於「深度複製」功能。 – 2012-04-04 14:17:07

+0

我試過你發給我的代碼,它仍然做同樣的事情,只讀第一個元素 – 2012-04-04 17:29:21

+0

相同的代碼適用於我 - http://timothyaaron.com/test.php。你確定它不是你的PHP? – 2012-04-04 18:31:25