javascript 如何将值从一个输入字段复制到另一个
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22646465/
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
How to Copy Value from one Input Field to Another
提问by Anuj Hari
I have two input fields:
我有两个输入字段:
<input type="text" id="one" name="one" />
<input type="text" id="two" name="two" />
I want to make it so that whatever that's typed into id one will automatically be put into id two.
我想让它使输入到 id one 中的任何内容都会自动放入 id 2 中。
Any ideas on how to do this? Possibly javascript needed?
关于如何做到这一点的任何想法?可能需要javascript?
回答by robbmj
Simply register an input
even handler with the source textfield
and copy the value to the target textfield
.
只需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());
});
});
<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" />