Onblur copy value in one field to another field

Hi

I have a form called “Form1” and I have an input field:
<input type=“text” id=“username_input” name=“usermame” onblur=“Test()”>

When the focus is lost on the above field, I would like to copy the value of this field to
this field here:
<input type=“text” name=“username2”>

I wrote a function called:
Test()
and have tried a couple of ways to copy the data from one field to another but it’s not working.

Can someone help me out pls?

Kath

Hi there,

bit quick and dirty, but this should do what you want:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>onblur example</title>
    <script>
      function test(){
        var f1 = document.getElementById("username_input");
        var f2 = document.getElementById("username_input2");
        f2.value = f1.value;
      }
    </script>
  </head>

  <body>
    <input type="text" name="usermame" id="username_input" value="Field 1" onblur="test()"><br /><br />
    <input type="text" name="username2" id="username_input2" value="Field 2">
  </body>
</html>

Inline JavaScript is not the best practice however, so it might be worth considering using an event listener.

Just to compare, here’s a version using jQuery and an event handler:

<!DOCTYPE  html  PUBLIC  "-//W3C//DTD  XHTML  1.0  Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html  xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta  http-equiv="Content-Type"  content="text/html;  charset=utf-8"  />
    <title>blur()  example - jQuery</title>
    <script  type="text/javascript"  src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
  </head>

  <body>
    <input  type="text"  name="usermame"  id="username_input"  value="Field  1"><br  /><br  />
    <input  type="text"  name="username2"  id="username_input2"  value="Field  2">

    <script>
      $(document).ready(function()  {
        $("#username_input").blur(function()  {
          $("#username_input2").val($("#username_input").val());
        });
      });
    </script>
  </body>
</html>

Here’s how it is normally done, in a less quick’n’dirty manner.

The form has an identifier, and the names of the elements within the form are used to access and manipulate them.


<form id="form1" method="..." action="...">
    <p><label>Username: <input name="username"></label></p>
    <p><label>Username 2: <input name="username2"></label></p>
</form>

And the script is placed at the end of the body:


var form = document.getElementById('form1');
form.elements.username.onblur = function () {
    var form = this.form;
    form.elements.username2.value = form.elements.username.value;
};