2008-11-23 28 views
11

我正在做一個簡單的表單來創建民意調查,因此我希望可以添加額外的輸入字段,以防用戶想在民意調查中使用更多選項。提交表單輸入框添加了javascript

我已經創建了Javascript代碼,它向表單添加了一個新的輸入字段,但是當表單提交時(我使用標準的提交按鈕),不會張貼動態添加的輸入字段。

有什麼方法可以將動態添加的字段發佈/識別爲表單的一部分?

<form id="myForm" method="post"> 
    <input type="submit"> 
    <input type="text" name="poll[question]"> 
    <input type="text" name="poll[option1]"> 
    <input type="text" name="poll[option2]"> 
</form> 
<a href="javascript:addOption();">Add option</a> 

<script> 
    var optionNumber = 3; //The first option to be added is number 3 
    function addOption() { 
    var theForm = document.getElementById("myForm"); 
    var newOption = document.createElement("input"); 
    newOption.name = "poll[option"+optionNumber+"]"; // poll[optionX] 
    newOption.type = "text"; 
    theForm.appendChild(newOption); 
    optionNumber++; 
    } 
</script> 

回答

4

你的代碼工作正常,如:

<?php 
    print_r($_REQUEST) 
?> 
<html> 
<body> 

<form id="myForm" method="post"> 
    <input type="submit"> 
    <input type="text" name="poll[question]"> 
    <input type="text" name="poll[option1]"> 
    <input type="text" name="poll[option2]"> 
</form> 
<a href="javascript:addOption();">Add option</a> 

<script> 
    var optionNumber = 3; //The first option to be added is number 3 
    function addOption() { 
     var theForm = document.getElementById("myForm"); 
     var newOption = document.createElement("input"); 
     newOption.name = "poll[option"+optionNumber+"]"; // poll[optionX] 
     newOption.type = "text"; 
     theForm.appendChild(newOption); 
     optionNumber++; 
    } 
</script> 
</body> 
</html> 

點擊添加選項兩次,你會得到

陣列([調查] =>陣列( [問題] => [option1] => [option2] => [option3] => [option4] =>)

2

你確定你沒有在這裏犯任何錯誤?

我複製你的代碼在一個新的頁面,並添加以下到ASP.NET頁面背後的代碼(它應該在任何框架的工作):

protected void Page_Load(object sender, EventArgs e) 
{ 
    foreach (string p in this.Request.Params.Keys) { 
     if (p.StartsWith("poll")) { 
      Response.Write(p + "&nbsp;&nbsp;" + this.Request.Params[p] + "<br />"); 
     } 
    } 
} 

我增加額外的字段,並進入測試值,輸出清楚地顯示了所有發佈回服務器的動態輸入字段。

這裏是輸出:

poll[question] test1 
poll[option1] test2 
poll[option2] test3 
poll[option3] test4 
poll[option4] test5 
poll[option5] test6 
poll[option6] test7 
12

我剛纔調試了我的網站,一個類似的問題。對我來說,事實證明,我的表格和表單標籤以「錯誤」的順序造成了這個問題。

破碎:

 
table 
    form 

工作:

 
form 
    table 

這指出了一些非常重要的。瀏覽器可能會呈現正常,並且表單可能正常工作,但格式不正確,但仍然可以通過沒有正確格式化的HTML來打破這種情況。也許我應該開始使用mod_tidy!

+0

我沒有意識到這可能會有這樣的效果,這對我有用。非常感謝:D – jwbensley 2011-09-05 10:02:18