Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - passing value from one input to another

Tags:

I have a form, with several input fields that are title, name, address etc

What I want to do, is to get these values and 'put them' into values of other input fields. For example

<label for="first_name">First Name</label> <input type="text" name="name" />  <label for="surname">Surname</label> <input type="text" name="surname" />  <label for="firstname">Firstname</label> <input type="text" name="firstname" disabled="disabled" /> 

So If I enter John in the first_name field, then the value of firstname will also be John.

Many thanks

like image 308
sipher_z Avatar asked May 05 '11 10:05

sipher_z


People also ask

What is the use of val() method in jQuery?

jQuery val() Method The val() method returns or sets the value attribute of the selected elements. When used to return value: This method returns the value of the value attribute of the FIRST matched element.

How to Get value from element in jQuery?

jQuery val() method is used to get the value of an element. This function is used to set or return the value. Return value gives the value attribute of the first element. In case of the set value, it sets the value of the attribute for all elements.


2 Answers

Assuming you can put ID's on the inputs:

$('#name').change(function() {     $('#firstname').val($(this).val()); }); 

JSFiddle Example

Otherwise you'll have to select using the names:

$('input[name="name"]').change(function() {     $('input[name="firstname"]').val($(this).val()); }); 
like image 97
Richard Dalton Avatar answered Nov 19 '22 23:11

Richard Dalton


It's simpler if you modify your HTML a little bit:

<label for="first_name">First Name</label> <input type="text" id="name" name="name" />  <label for="surname">Surname</label> <input type="text" id="surname" name="surname" />  <label for="firstname">Firstname</label> <input type="text" id="firstname" name="firstname" disabled="disabled" /> 

then it's relatively simple

$(document).ready(function() {      $('#name').change(function() {       $('#firstname').val($('#name').val());     }); }); 
like image 33
Russ Clarke Avatar answered Nov 19 '22 22:11

Russ Clarke