2013-08-20 45 views
2

我試圖在<div id="screens"> </div>內部創建文本框。我有一個下拉菜單,我選擇要創建的文本框的數量。如何從javascript動態創建文本框

我在這裏寫的JavaScript代碼是不工作:

代碼:

function create(param) { 
    document.getElementById("screens").innerHTML="";   
    for(var i = 0; i < param; i++) { 
     alert(i); 
     document.write('<input type="text" name="Fname">'); 
    } 
} 

這是通過清除當前頁面中的所有內容添加文本框,但我想添加文本框到<div id="screen"> </div>。我怎樣才能做到這一點?

+0

請閱讀有關一些文檔['document.write()的'](https://developer.mozilla.org/en-US/docs/Web/API/document.write)。您已在代碼中使用['innerHTML'](https://developer.mozilla.org/en-US/docs/Web/API/element.innerHTML),爲什麼不重用它? – Teemu

回答

5

嘗試是這樣的:

function create(param) { 
    var s= ""; 
    for(var i = 0; i < param; i++) { 
     s+= '<input type="text" name="Fname">'; //Create one textbox as HTML 
    } 
    document.getElementById("screens").innerHTML=s; 
} 
1

由於您在問題中標記了jQuery,因此我假設您使用的是jQuery。

function create(param) { 
    'use strict'; 

    var i; 

    $("#screens").empty(); 

    for(i = 0; i < param; i += 1) { 
     $('#screens').append('<input type="text" name="Fname">'); 
    } 
} 

jsFiddle

純JavaScript實現應該是這樣的:

function create(param) { 
    'use strict'; 

    var i, target = document.getElementById('screens'); 
    target.innerHTML = ''; 

    for(i = 0; i < param; i += 1) { 
     target.innerHTML += '<input type="text" name="Fname">'; 
    } 
} 

jsFiddle

0
function create(param) { 
    var screens = document.getElementById('screens'), 
     innerHTML = '', 
     i; 

    for (i = 0; i < param; i += 1) { 
     alert(i); 
     innerHTML += '<input type="text" name="Fname">'; 
    } 

    screens.innerHTML = innerHTML; 
} 
0
function create(param) { 
    var target = document.getElementById('screens'), 
     oFrag=document.createDocumentFragment(); 

    target.innerHTML = ''; 

    for (var i = 0; i < param; i++) { 
     var iptNode = document.createElement("input"); 
     iptNode.setAttribute("type", "text"); 
     iptNode.setAttribute("name", "Fname"); 
     oFrag.appendChild(iptNode); 
    } 

    target.appendChild(oFrag); 
} 
0
<script> 
var newInput4=document.createElement("input"); 
newInput4.className="form-control "; 
newInput4.name="totalunit"+instance; 
newInput4.placeholder="Unit"; 
newInput4.type="text"; 
</script>