如何将值从一个输入字段复制到另一个输入字段

Anu*_*ari 1 html javascript input

我有两个输入字段:

<input type="text" id="one" name="one" />
<input type="text" id="two" name="two" />
Run Code Online (Sandbox Code Playgroud)

我想这样做,以便输入id中的任何内容都会被自动放入id 2中.

关于如何做到这一点的任何想法?可能需要javascript吗?

rob*_*bmj 11

只需input在源代码中注册一个偶数处理程序,textfield然后将值复制到目标textfield.

window.onload = function() {
    var src = document.getElementById("one"),
        dst = document.getElementById("two");
    src.addEventListener('input', function() {
        dst.value = src.value;
    });
};

// jQuery implementation

$(function () {
    var $src = $('#three'),
        $dst = $('#four');
    $src.on('input', function () {
        $dst.val($src.val());
    });
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
</script>

<strong> With vanilla JavaScript</strong>
<br />
<input type="text" id="one" name="one" />
<input type="text" id="two" name="two" />

<br />
<br />

<strong>With jQuery</strong>
<br />
<input type="text" id="three" name="three" />
<input type="text" id="four" name="four" />
Run Code Online (Sandbox Code Playgroud)

小提琴

  • 我知道你知道,但它会给年轻的开发者带来一些困惑:)现在没关系. (2认同)