Set value to input field onchange from other input field

27,494

Simply assign an identifier to each input, and pass the input to the function:

<input type="text" id="myInput1" onchange="myChangeFunction(this)" placeholder="type something then tab out" />
<input type="text" id="myInput2" />

<script type="text/javascript">
  function myChangeFunction(input1) {
    var input2 = document.getElementById('myInput2');
    input2.value = input1.value;
  }
</script>

You pass input1 to the function as an argument, then we get the value of input1 and assign it as the value to input2 after finding it in the DOM.

Note that the change event will only fire on a text input if you remove focus. So for example you'll have to tab out of the field to get field 2 to get updated. If you want you could use something else like keyup or keypress to get a more live update.

You can also do this without using an HTML attribute which is a little cleaner:

<input type="text" id="myInput1" />
<input type="text" id="myInput2" />

<script type="text/javascript">
  var input1 = document.getElementById('myInput1');
  var input2 = document.getElementById('myInput2');

  input1.addEventListener('change', function() {
    input2.value = input1.value;
  });
</script>
Share:
27,494
eqinna
Author by

eqinna

Updated on March 20, 2020

Comments

  • eqinna
    eqinna about 4 years

    I'm completely new to Javascript, and currently I'm trying to set a value to an input field triggered by an onchange event from another input field.

    Code sample - input field 1:

    <input type='text' onchange='methodThatReturnsSomeValue()'>
    

    Now I want to assign the following input field's value with the returned one from the method triggered from onchange above:

    <input type='text'>
    

    Does anyone know how this can be solved?

  • eqinna
    eqinna over 5 years
    I just tried your code on the following site: jsfiddle.net but on focus out it doesn't assign my typed value to input2. :-(
  • Timothy Fisher
    Timothy Fisher over 5 years
    Can you save the fiddle and send the link to it here?