2010-02-18 166 views
10

假設在文本框中輸入了一個條目。是否可以在第二個文本框中保留相同的輸入文本?如果是這樣,這是如何完成的?將一個文本框的內容複製到另一個文本框

<html> 
<label>First</label><input type="text" name="n1" id="n1"> 
<label>Second</label><input type="text" name="n1" id="n1"/> 
</html> 

謝謝。

回答

28
<script> 
function sync() 
{ 
    var n1 = document.getElementById('n1'); 
    var n2 = document.getElementById('n2'); 
    n2.value = n1.value; 
} 
</script> 
<input type="text" name="n1" id="n1" onkeyup="sync()"> 
<input type="text" name="n2" id="n2"/> 
+0

謝謝......................... – Hulk 2010-02-18 08:31:09

+0

簡單,同步,完美! – Drew 2011-11-14 00:38:40

+0

您可以通過添加兩個參數來概括此函數:'input_field'(通常以this的形式傳入)和表示要複製到的元素的ID的字符串。然後你可以用'input_field'替換n1變量。 – 2013-07-11 16:39:48

3
<html> 
<script type="text/javascript"> 
function copy() 
{ 
    var n1 = document.getElementById("n1"); 
    var n2 = document.getElementById("n2"); 
    n2.value = n1.value; 
} 
</script> 
<label>First</label><input type="text" name="n1" id="n1"> 
<label>Second</label><input type="text" name="n2" id="n2"/> 
<input type="button" value="copy" onClick="copy();" /> 
</html> 
2

那麼,你有兩個具有相同ID的文本框。 Id應該是唯一的,所以你應該改變這一點。

要設置從一個文本框到另一個價值getElementById()一個簡單的電話就足夠了:

document.getElementById("n1").value= document.getElementById("n2").value; 

(假設,當然你給你的secodn文本框的n2一個id)

領帶這最多隻需點擊一下按鈕即可使其工作。

+1

'.value'你打算在那裏輸入,對嗎? – 2010-02-18 08:25:34

2

這個工作對我來說,它不使用JavaScript:

<form name="theform" action="something" method="something" /> 
<input type="text" name="input1" onkeypress="document.theform.input2.value = this.value" /> 
<input type="text" name="input2" /> 
</form> 

I found the code here

+2

從技術上講,_does_使用Javascript,但你是對的,你不必導入一個單獨的腳本來做到這一點。 – 2013-07-11 16:36:33

5

更有效的是可以做到的是: 對於一個誰將會看到帖子現在應該使用JavaScript的最佳做法。

<script> 
function sync(textbox) 
{ 
    document.getElementById('n2').value = textbox.value; 
} 
</script> 
<input type="text" name="n1" id="n1" onkeyup="sync(this)"> 
<input type="text" name="n2" id="n2"/> 
+0

投票使用最佳做法! – 2014-12-29 22:44:06

1

使用事件「oninput」。這提供了更強大的行爲。複製粘貼時它也會觸發複製功能。

+1

你可以添加一個這樣的例子嗎? – 2016-07-13 10:40:40

相關問題