javascript 将值设置为输入字段 onchange 从其他输入字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53637874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 10:15:44  来源:igfitidea点击:

Set value to input field onchange from other input field

javascripthtmldom-eventsonchange

提问by eqinna

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

我对 Javascript 完全陌生,目前我正在尝试onchange为由另一个输入字段的事件触发的输入字段设置一个值。

Code sample - input field 1:

代码示例 - 输入字段 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 onchangeabove:

现在我想用从onchange上面触发的方法返回的值分配以下输入字段的值:

<input type='text'>

Does anyone know how this can be solved?

有谁知道如何解决这个问题?

回答by Timothy Fisher

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 input1to the function as an argument, then we get the value of input1 and assign it as the value to input2after finding it in the DOM.

您将input1函数作为参数传递给函数,然后我们获取 input1 的值,input2并在 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 keyupor keypressto get a more live update.

请注意,如果您移除焦点,更改事件只会在文本输入上触发。因此,例如,您必须退出该字段才能使字段 2 更新。如果你愿意,你可以使用其他类似的东西keyupkeypress获得更实时的更新。

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

您也可以在不使用更简洁的 HTML 属性的情况下执行此操作:

<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>