2016-03-02 29 views
0

我希望用戶單擊按鈕並出現表單。但不管他們按了多少次這個按鈕,表格都會出現。按照它們創建的順序依次排列。我想在JavaScript中實現。在onclick上動態添加輸入元素

我不是專業人士,我正在自學。只是想知道我是否可以說:

<button id="new"><span class="glyphicon glyphicon-plus"> Add New Add-on</span></button> 

這可能嗎?用我讀過的,我想出了這個。但正如我所預料的那樣,它不起作用。

<input type="button" id="new" name="new" value="Add New Add-On" class="btn" onclick="addFields()"> 

<div id="New_Form"/> 

</div> 

<script> 
    function addFields(){ 
     var button = document.getElementById("new").value; 
     var container = document.getElementById("New_Form"); 
     while (New_Form.hasChildNodes()) { 
      New_Form.removeChild(New_Form.lastChild); 
     } 
     for (i=0;i<number;i++){ 
      New_Form.appendChild(document.createTextNode("new " + (i+1))); 
      var input = document.createElement("input"); 
      input.type = "button"; 
      New_Form.appendChild(input); 
      New_Form.appendChild(document.createElement("br")); 
     } 
    } 
</script> 
+0

爲什麼jQuery標籤? – j08691

+0

「並出現一個表單」,但您的代碼添加了輸入,而不是「表單」,請通過重新編輯或編輯問題來澄清。 –

回答

0

你「唯一的」錯誤是你試圖錯誤地訪問div。此外,「號碼」沒有指定,所以什麼都沒有發生。

我解決了這個問題,並且一路上評論了我的/你的代碼。請注意,我可能無法正確理解您的問題。您可以進一步詢問並指定您的需求。 從我的角度來看,這個腳本到目前爲止有點無用。但繼續學習!

<input type="button" id="new" name="new" value="Add New Add-On" class="btn" onclick="addFields()"> 

<div id="New_Form"/> 
    <!--- Here goes the new form! --> 
</div> 

<script> 
    function addFields(){ 
     // What did you want to accomplish here? 
     //var button = document.getElementById("new").value; 
     // You save the div with id "New_Form" into the variable container 
     var container = document.getElementById("New_Form"); 
     // Now, why not use it then? :) 
     while (container.hasChildNodes()) { 
      // Removes all childs. NOTE: This will cause just one(!) form to appear in total! 
      container.removeChild(container.lastChild); 
     } 
     // Number?? You need to specify some value here. I take 10 as an example. 
     for (i=0; i < 10; i++) { 
      // Again, use "container" 
      container.appendChild(document.createTextNode("new " + (i+1))); 
      var input = document.createElement("input"); 
      input.type = "button"; 
      container.appendChild(input); 
      container.appendChild(document.createElement("br")); 
     } 
    } 
</script> 
+0

我要試試這個。如果它的工作,我會感到非常愚蠢的哈哈。我想能夠按下按鈕,並添加儘可能多的表單域,我可能可以 – jerneva

+0

問題是,爲什麼你遍歷你的「New_Form」div的所有孩子,並刪除它們? –

+0

我不知道該怎麼辦,我剛剛在閱讀博客,這是他們的建議。一種新的Javascript。腳本的整個想法是允許用戶按照自己的喜好添加儘可能多的產品。然後設置它的樣式並在稍後的日期將表單/輸入切換爲切換 – jerneva