将值设置为与其他输入字段发生变化时的输入字段 [英] Set value to input field onchange from other input field

查看:66
本文介绍了将值设置为与其他输入字段发生变化时的输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java语言的新手,目前我正在尝试为由另一个输入字段中的onchange事件触发的输入字段设置值.

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.

代码示例-输入字段1:

Code sample - input field 1:

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

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

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

有人知道如何解决吗?

推荐答案

只需为每个输入分配一个标识符,然后将输入传递给函数:

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>

您将input1作为参数传递给函数,然后我们在DOM中找到input1的值并将其作为input2的值赋值.

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.

请注意,仅当您删除焦点时,更改事件才会在文本输入上触发.因此,例如,您将不得不跳出字段以获取字段2进行更新.如果您愿意,可以使用keyupkeypress之类的其他东西来获取更实时的更新.

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.

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

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>

这篇关于将值设置为与其他输入字段发生变化时的输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆