2016-06-12 11 views
0

當我運行這個「你輸入:插入文本」出現一秒鐘,然後消失,文本框自行清除。我花了3個小時,我看不出我犯了什麼錯誤。任何幫助表示讚賞!謝謝。試圖從文本框中讀取用戶輸入並在javascript下打印出來?

<!DOCTYPE html> 
<html> 

<head> 
<title> Basic JavaScript </title> 

<script type = "text/javascript"> 
function Copier() { 

var firstWord= document.getElementById("Word1").value; 
document.write("You entered: " + firstWord); 

} 

</script> 

</head> 
<body> 


<form> 

Word Number 1: 
<input type = "text" id = "Word1" > 
<br> 

<button onclick = "Copier()">Copy Text Box 1</button> 

</form> 

</body> 

</html> 

回答

0

你不需要表單標籤。

如果您使用的是在你輸入的表單標籤,瀏覽器假定存在應該像定義的方法:

<form action="post/get" url="some-file.php"> 

只要你的JavaScript已經抓住了輸入時,它得到的沖洗出來的表單(重新)操作,它指向沒有指定的文件。

只需離開表單標籤並通過輸入字段本身獲取值。

<!DOCTYPE html> 
<html> 
<head> 
<title> Basic JavaScript </title> 
<style> 
input[type="text"] { 
    border: 1px solid #565656; 
    padding: 2px; 
    color: black; 
} 
#display { 
    position: relative; 
    top: 0; 
    width: 300px; 
    height: 30px; 
} 
</style> 
<script type = "text/javascript"> 
function Copier() { 
var firstWord= document.getElementById("Word1").value; 
var box = document.getElementById('display'); 
box.innerHTML = "You entered:" + firstWord; 
} 
</script> 
</head> 
<body> 
Word Number 1: 
<input type="text" id="Word1" > 
<br> 
<button onclick = "Copier()">Copy Text Box 1</button> 
<div id="display"></div> 
</body> 
</html> 
+0

謝謝,表單標籤把我扔了! – Luxpride

+0

不客氣。 – 2016-06-12 21:54:58

0

請勿使用document.write(),因爲這很危險。擁有自己的id創建一個單獨的元素,並使用innerHTML

function Copier() { 
 
    document.getElementById("output").innerHTML = "You entered: " + document.getElementById("Word1").value; 
 
}
<form> 
 

 
    Word Number 1: 
 
    <input type = "text" id = "Word1" > 
 
    <br> 
 

 
    <button onclick = "Copier()">Copy Text Box 1</button> 
 
    <p id="output"></p> 
 
</form>

0

使用用戶'user2521387'關於表單標記的說法。你應該刪除表單標籤,如果你不想使用innerHTML,你可以這樣做:

function Copier() { 
    var firstWord = document.getElementById("Word1").value; 
    var box = document.getElementById('display'); 

    //clear all childs of div with id 'display' 
    while (box.firstChild) { // whilte first child is valid 
     box.removeChild(box.firstChild); // removes first child 
    } 
    var p = document.createElement("p"); //create p tag 
    p.appendChild(document.createTextNode("You entered:" + firstWord)); 

    box.appendChild(p); //add p tag to div 

} 
相關問題