jQuery - passing value from one input to another

2019-01-22 14:41发布

问题:

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

回答1:

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());
});


回答2:

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());
    });
});


回答3:

Add ID attributes with same values as name attributes and then you can do this:

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


回答4:

Get input1 data to send them to input2 immediately

<div>
<label>Input1</label>
 <input type="text" id="input1" value="">
</div>

</br>
<label>Input2</label>
<input type="text" id="input2" value="">

<script type="text/javascript">
        $(document).ready(function () {
            $("#input1").keyup(function () {
                var value = $(this).val();
                $("#input2").val(value);
            });
        });
</script>