views:

471

answers:

3

Hi There,

Is there an easy way to populate one form field with duplicate content from another form field? Maybe using jQuery or javascript?

Thanks, Jack

+3  A: 

It is easy in javascript using jQuery:

$('#dest').val($('#source').val());
Darwin
Thanks Darwin. How would I trigger it so that when I have filled in say the email address field, then click inside the user name field, it adds the email address to the username field.
Jackson
+3  A: 

You just have to assign the field values:

// plain JavaScript
var first = document.getElementById('firstFieldId'),
    second = document.getElementById('secondFieldId');

second.value = first.value;

// Using jQuery
$('#secondFieldId').val($('#firstFieldId').val());

And if you want to update the content of the second field live, you could use the change or keyup events to update the second field:

first.onkeyup = function () { // or first.onchange
  second.value = first.value;
};

With jQuery:

$('#firstFieldId').keyup(function () {
  $('#secondFieldId').val(this.value);
});

Check a simple example here.

CMS
+3  A: 

In Native Javascript:

var v1 = document.getElementById('source').value;
document.getElementById('dest').value = v1;
Crimson