如何将值从一个输入字段复制到另一个 [英] How to Copy Value from one Input Field to Another

查看:77
本文介绍了如何将值从一个输入字段复制到另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个输入字段:

<input type="text" id="one" name="one" />
<input type="text" id="two" name="two" />

我想这样做,以便将键入id 1的任何内容自动放入id 2.

I want to make it so that whatever that's typed into id one will automatically be put into id two.

关于如何执行此操作的任何想法?可能需要JavaScript吗?

Any ideas on how to do this? Possibly javascript needed?

推荐答案

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

Simply register an input even handler with the source textfield and copy the value to the target 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());
    });
});

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

小提琴

这篇关于如何将值从一个输入字段复制到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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