javascript 同步 2 个输入字段,可以使用 jQuery 来完成吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8803416/
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
Synchonise 2 input fields, can it be done using jQuery?
提问by Satch3000
Can jQuery synchronise or copy the text of one input field to another when input A is modified? For example:
修改输入A时,jQuery可以同步或复制一个输入字段的文本到另一个输入字段吗?例如:
<input id="input_A" type="text" /> ...If I type something here
<input id="input_B" type="text" /> ... It will be copied here
Can jQuery Do this?
jQuery 可以做到这一点吗?
回答by Rory McCrossan
Try this:
试试这个:
$("#input_A").bind("keyup paste", function() {
$("#input_B").val($(this).val());
});
For jQuery 1.7+ use on
:
对于 jQuery 1.7+ 使用on
:
$("#input_A").on("keyup paste", function() {
$("#input_B").val($(this).val());
});
– Update August 2017–
– 2017年8 月更新–
The input
event is now well supported, so you can use that in place of combining both keyup
and paste
events:
该input
事件现在得到了很好的支持,因此您可以使用它来代替结合keyup
和paste
事件:
$("#input_A").on("input", function() {
$("#input_B").val(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input_A" type="text" />
<input id="input_B" type="text" />
回答by grimmdude
Late answer, but I prefer this way since it doesn't require multiple element ids:
迟到的答案,但我更喜欢这种方式,因为它不需要多个元素 ID:
$('input.sync').on('keyup paste', function() {
$('input.sync').not(this).val($(this).val());
});
Garrett
加勒特
回答by abuduba
During writing, pasting, etc value will be copied.
In jQuery < 1.7 instead on
use bind
.
在写入、粘贴等过程中,值将被复制。在 jQuery < 1.7 中改为on
使用bind
.
$( "#input_A" ).on( "paste keyup", function() {
$( "#input_B" ).val( $( this ).val() );
});
回答by FishBasketGordo
Yes, it can. Bind a keypress or keyup event and copy over the value:
是的,它可以。绑定 keypress 或 keyup 事件并复制值:
$('#input_A').keyup(function() {
$('#input_B').val($(this).val());
});
Or, if you only want the value to be copied after the user is finished editing it, use the blur event with the same handler. This has an added advantage that if the user pastes text into input_A
, it also will be copied into input_B
.
或者,如果您只想在用户完成编辑后复制该值,请使用具有相同处理程序的 blur 事件。这有一个额外的好处,如果用户将文本粘贴到input_A
,它也会被复制到input_B
.
$('#input_A').blur(function() {
$('#input_B').val($(this).val());
});
Here's a working example with keyupand one with blur.