开发者

Copy contents of one textbox to another

Suppose an entry is made in a textbox. Is it possible to retain the same entered text in a second text box? If so, how is this done?

<html>
      <label>First</label>
      <input type="text" name="n1" id="n1">
      <label>Second</label>
      <input type="text" name="n1" id="n1"/>
<开发者_JAVA百科;/html>


<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"/>


More efficiently it can be done as : For the one who will see the post now should use best practices of 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"/>


<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>


Well, you have two textboxes with the same ID. An Id should be unique, so you should prbably change this.

To set the value from one text box to another a simple call to getElementById() should suffice:

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

(assuming, of course you give your secodn text box an id of n2)

Tie this up to a button click to make it work.


This worked for me and it doesn't use 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


Use event "oninput". This gives a more robust behavior. It will also trigger the copy function when you copy paste.


You can this way also used copy contents of one textbox to another

function populateSecondTextBox() {
        document.getElementById('txtSecond').value = document.getElementById('txtFirst').value;
}
<label>Write Here :</label> 
<input type="text" id="txtFirst" onkeyup="populateSecondTextBox();" />
<br>
<label>Will be copied here :</label>
<input type="text" id="txtSecond" />

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜