【问题标题】:How to change an <input> field's VALUE attribute in real time with JavaScript?如何使用 JavaScript 实时更改 <input> 字段的 VALUE 属性?
【发布时间】:2018-12-18 17:33:38
【问题描述】:

我想在用户输入另一个 input 字段时实时更改 input 字段的值,最好使用常规 JS 而不是 JQuery。

示例:用户在 #input_1 中输入一个随机值,同时,#input_2 接收用户输入的任何内容并将其设置为该值。

如果用户从 #input_1 值中删除一个数字,#input_2 会跟随并从其值中删除相同的数字。

这一切都是实时,最好无需按下按钮即可触发执行此操作的功能。

【问题讨论】:

  • 你用谷歌搜索过这个吗?
  • @YaakovAinspan 试过了,但找不到任何适合我的东西。
  • inp1.oninput=x=&gt;inp2.value=inp1.value;
  • jsfiddle.net/yak613/dn6h0fre 这花了我不到一分钟的时间 :)
  • 不捕获按钮按下的唯一方法是使用超时/间隔。这样效率会低很多。

标签: javascript html forms input


【解决方案1】:

简单;)

<input id="input1" onkeyup="document.getElementById('input2').value=this.value" />
<input id="input2" />

【讨论】:

  • 这当然可以,但一般建议不要使用内联 Javascript 属性。这样做会鼓励代码重复并模糊关注点的分离。
  • @RobertAKARobin 取决于使用老兄;)
【解决方案2】:

有很多方法可以实现这一点。以下是我的做法:

HTML:

<input id="sourceField" />
<input id="destinationField" />

JS:

// When the page is done loading and rendering...
window.addEventListener('DOMContentLoaded', ()=>{
    // Get the appropriate elements
    const sourceField = document.getElementById('sourceField')
    const destinationField = document.getElementById('destinationField')

    // When the user types some input into the first text field...
    sourceField.addEventListener('input', ()=>{
        // Set the value of the destination field to the value of the source field.
        destinationField.value = sourceField.value
    })
})

【讨论】:

  • 需要DOMContentLoaded吗?只要它在元素下方就可以了
  • @YaakovAinspan 你说得对,但我们不知道 OP 会把这个 JS 放在哪里,所以我更喜欢包含它。
  • 我会把它添加到页面本身,如果这就是你的意思。不在单独的 .js 文件中。
  • @PolarDog 无论您的 JS 是在单独的文件中还是在 HTML 中内联,如果加载它的 &lt;script&gt; 元素在您的 HTML 中的 &lt;input&gt; 元素之后,您不需要需要DOMContentLoaded。但我喜欢将 &lt;script&gt; 元素放在 HTML 的 &lt;head&gt; 中。
  • 我把它放在我的&lt;head&gt; 之下,但在我的&lt;body&gt; 之上。
【解决方案3】:

你可以这样做

您需要选择第一个输入(在事件中)并从该输入中获取值并在第二个输入中更新。

function handle(e){
  var input1 = document.getElementById('input1').value;
  console.log(input1)
  document.getElementById('input2').value = input1;
}
<input id='input1' onkeyup="handle()" value=""/>
<input id='input2'  value="" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    相关资源
    最近更新 更多