2012-10-01 18 views
0

消失,我想有一個Add another field按鈕創建每次按下按鈕時,文本字段<input type="text" name="pet">添加一個文本字段點擊按鈕使用javascript:除了文本字段中的所有內容上點擊

我目前有this code

<html> 
<head> 
<script>  
function add_field() 
{ 
    document.write('<input type="text" name="pet">'); 
}; 
</script> 
</head> 
<body> 

<form name="input" method="get"> 
Favourite pets:<br> 
<input type="text" name="pet"> 
<button type="button" onclick="add_field()">Add another field</button><br> 
<input type="submit" value="Submit"><br> 
</form> 

</body> 
</html> 

但是,當我按下按鈕Add another field我剛剛得到一個頁面,只有一個文本字段,我的所有其他內容消失。 如何在添加其他文本字段時仍保留其他html內容?

回答

1

這條線:

document.write('<input type="text" name="pet">'); 

將與插入標記替換整個文檔。如果你想追加輸入字段,你需要找到你想追加的表單,創建輸入字段並追加它。嘗試類似:

var form = document.getElementsByTagName('form')[0], 
    input = document.createElement('input'); 

input.setAttribute('type', 'text'); 
input.setAttribute('name', 'pet'); 
form.appendChild(input); 

這將在窗體的末尾插入input。您可以使用其他方法,例如insertBefore將輸入字段放在需要的位置。

或者使用jQuery。

相關問題