2009-12-23 27 views
0

所以當我點擊按鈕時,javascript添加了新的字段。目前它將新的文本框添加到邊..有沒有辦法讓它在下面添加?我猜想好像有一個
。 這是代碼。謝謝!使用JavaScript來添加表單域..但下面,而不是一邊?

<html> 
<head> 
    <script type="text/javascript"> 
     var instance = 1; 

     function newTextBox(element) 
     {  
      instance++; 
      var newInput = document.createElement("INPUT"); 
      newInput.id = "text" + instance; 
      newInput.name = "text" + instance; 
      newInput.type = "text"; 
      //document.body.write("<br>"); 
      document.body.insertBefore(newInput, element); 
     } 
    </script> 
</head> 


<body> 
    <input id="text2" type="text" name="text1"/> <br> 
    <input type="button" id="btnAdd" value="New text box" onclick="newTextBox(this);" /> 
</body> 

回答

2

插入<br/>標籤盈插入的輸入或更好,把輸入到一個div和控制它與CSS的外觀。

0

添加到您的函數的末尾:

document.body.insertBefore(document.createElement("br"), element); 

全碼:

<html> 
<head> 
     <script type="text/javascript"> 
       var instance = 1; 

       function newTextBox(element) 
       {    
         instance++; 
         var newInput = document.createElement("INPUT"); 
         newInput.id = "text" + instance; 
         newInput.name = "text" + instance; 
         newInput.type = "text"; 
         //document.body.write("<br>"); 
         document.body.insertBefore(newInput, element); 

         document.body.insertBefore(document.createElement("br"), element); 
       } 
     </script> 
</head> 


<body> 
     <input id="text2" type="text" name="text1"/> <br> 
     <input type="button" id="btnAdd" value="New text box" onclick="newTextBox(this);" /> 
</body> 
</html> 
0

只需創建一個<br>元素以同樣的方式,把它之間。

var newBr = document.createElement("BR"); 
document.body.insertBefore(newBr, element); 

或使用CSS。 display:block可能是是有價值的。

0

你既可以插入br元素的新的輸入之後,或者把它包一個div的元素:

function newTextBox(element) {     
    instance++; 
    var newInput = document.createElement("INPUT"); 
    newInput.id = "text" + instance; 
    newInput.name = "text" + instance; 
    newInput.type = "text"; 

    var div = document.createElement('div'); 
    div.appendChild(newInput); 
    document.body.insertBefore(div, element); 
} 

檢查上面的例子here

相關問題