2016-05-15 62 views
1

程序顯示的表格中有作爲默認文本的輸入。請我想知道如何將其替換爲具有ID的輸入文本框。謝謝如何在javascript中創建輸入文本框

<html> 
<body> 

</body> 
<script> 
function tableCreate(){ 
var body = document.body, 
tbl = document.createElement('table'); 
tbl.style.width = '100px'; 
tbl.style.border = '2px solid black'; 
var n=5 
for(var i = 0; i < n; i++){ 
    var tr = tbl.insertRow() 
    var td = tr.insertCell(0); 
    var tf = tr.insertCell(0); 
    td.appendChild(document.createTextNode('input')); 
    tf.appendChild(document.createTextNode('input')); 
    td.style.border = '2px solid black'; 
    tf.style.border = '2px solid black'; 
    } 

body.appendChild(tbl); 
} 
tableCreate(); 
</script> 
</html> 

回答

1

替代document.createElement("input")document.createTextNode("input");創建一個form元素,在創建的每個input元素處包含name屬性屬性;設置id"input-a" + i"input-b" + i;附加input type="submit"form元素;創建追加到table元素form

<body> 
 
    <script> 
 
    function tableCreate() { 
 
     var body = document.body, 
 
     tbl = document.createElement('table'); 
 
     tbl.style.width = '100px'; 
 
     tbl.style.border = '2px solid black'; 
 
     var n = 5 
 
     for (var i = 0; i < n; i++) { 
 
     var tr = tbl.insertRow(); var td = tr.insertCell(0); 
 
     var tf = tr.insertCell(0); 
 
     var input = document.createElement('input'); 
 
     input.name = "input-a" + i; 
 
     input.id = "input-a" + i; 
 
     input.value = ""; 
 
     var clone = input.cloneNode(); 
 
     clone.name = "input-b" + i; 
 
     clone.id = "input-b" + i; 
 
     td.appendChild(clone); 
 
     tf.appendChild(input); 
 
     td.style.border = '2px solid black'; 
 
     tf.style.border = '2px solid black'; 
 
     } 
 
     var form = document.createElement("form"); 
 
     form.appendChild(tbl); 
 
     body.appendChild(form); 
 
     var submit = document.createElement("input"); 
 
     submit.type = "submit"; 
 
     form.appendChild(submit) 
 
    } 
 
    tableCreate(); 
 
    </script> 
 
</body >

+0

非常感謝,它的工作。但是,我希望輸入元素擁有id,因此我可以提取這些值,以及如何創建一個將一次提交所有輸入框的提交按鈕。謝謝你的幫助 – chika

+0

@chika查看更新後的帖子 – guest271314

+0

非常感謝。我很感激 – chika

相關問題