user1022772
user1022772

Reputation: 651

Auto populate one field based on another javascript

I'm not very familiar with javascript, but trying to populate username field with what the user types into the email field. Also don't want user to be able to edit username field after being auto populated from the email field. Will 'disable' still allow JS to work?

<script type="text/javascript">
    var first = document.getElementById('email'),
    second = document.getElementById('username');

    first.onkeyup = function () { 
        second.value = first.value;
    };
</script>

my form has a number of fields. One of them has ID and name of 'username' and another field has name and ID of 'email'. Why can't I get this to work? is my JS syntax wrong?

Upvotes: 0

Views: 3057

Answers (2)

AndrewPolland
AndrewPolland

Reputation: 3071

It's possible your issue is being cause by calling the JavaScript before the html elements have been created. A simple solution is to place your JS at the bottom of the page.

<html>
   <head>
   </head>
   <body>

      --ALL YOUR HTML HERE--

      <script type="text/javascript">
         var first = document.getElementById('email'),
         second = document.getElementById('username');

         first.onkeyup = function () { 
            second.value = first.value;
         };
      </script>
   </body>
</html>

Upvotes: 0

user1022772
user1022772

Reputation: 651

Jasonscript pointed out that I needed to have script at bottom of page. Moved it and it works.

Upvotes: 0

Related Questions