2010-02-18 6 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

+0

간단하고, 동시적이고, 완벽! – Drew

+0

이 함수는'input_field' (일반적으로'this'로 전달 될 것입니다)와 복사하고자하는 원소의 id를 나타내는 문자열을 추가하여 일반화 할 수 있습니다. 그런 다음 n1 변수를'input_field'로 대체 할 수 있습니다. –

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는 고유해야하므로이 값을 변경해야합니다.

(물론 당신이 당신의 secodn 텍스트 상자를 n2의 ID를 제공, 가정)
document.getElementById("n1").value= document.getElementById("n2").value; 

타이 :

getElementById()에 대한 간단한 호출이 충분해야 하나 개의 텍스트 상자에서 다른 값을 설정하려면 이 버튼을 클릭하면 작동합니다. 자바 스크립트

+1

'.value'여기에 입력하는 것이 좋습니다. –

2

이 나를 위해 일한 그리고 그것은 사용하지 않습니다

<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

기술적으로 자바 스크립트를 사용하지는 않지만 별도의 스크립트를 가져올 필요가 없습니다. –

5

그것으로 수행 할 수 있습니다 : 이제 게시물을 참조해야 할 일을 위해 자바 스크립트의 모범 사례를 사용하십시오.

<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

베스트 프랙티스 사용을 위해 투표하십시오! –

1

이벤트 "oninput"을 사용하십시오. 이것은보다 강력한 동작을 제공합니다. 또한 붙여 넣기를 복사 할 때 복사 기능을 트리거합니다.

+1

예를 들어 추가 할 수 있습니까? –

관련 문제