javascript 当用户在文本框中键入值时,在另一个文本框中显示一个文本框值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3593679/
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
Showing one text box value in another text box while user type the value to the text box
提问by Rangana Sampath
Is there a way to get the value from one text box and add it to another using jQuery dynamically when user is typing the value to the text box? can someone please explain the method if there is any such thing?
当用户在文本框中键入值时,有没有办法从一个文本框中获取值并使用 jQuery 动态地将其添加到另一个文本框中?如果有这样的事情,有人可以解释一下方法吗?
regrds, Rangana
再见,兰加纳
回答by Yi Jiang
You mean something like http://jsfiddle.net/ZLr9N/?
你的意思是像http://jsfiddle.net/ZLr9N/?
$('#first').keyup(function(){
$('#second').val(this.value);
});
Its really simple, actually. First we attach a keyupevent handler on the first input. This means that whenever somebody types something into the first input, the function inside the keyup()function is called. Then we copy over the value of the first inputinto the second input, with the val()function. That's it!
其实很简单。首先,我们keyup在第一个input. 这意味着每当有人在 first 中输入内容时input,函数内的keyup()函数就会被调用。然后我们使用函数将第一个的值复制input到第二个中。而已!inputval()
回答by Kelsey
$('#textbox1').keypress(function(event) {
$('#textbox2').val($('#textbox1').val() + String.fromCharCode(event.keyCode));
});
This will ensure that textbox2always matches the value of textbox1.
这将确保textbox2始终匹配 的值textbox1。
Note:You can use the keyupevent as others have suggested but there will be a slight lag possibly. Test both solutions and this one should 'look' better. Test them both and hold down a key or type real fast and you will notice a significant lag using keyupsince keypresstriggers before the keyupevent even happens.
注意:您可以keyup按照其他人的建议使用该事件,但可能会有轻微的延迟。测试这两种解决方案,这个应该“看起来”更好。测试它们并按住一个键或真正快速地键入,您会注意到使用keyup自keypress触发器keyup甚至在事件发生之前显着滞后。
回答by Pramendra Gupta
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"
>
<html lang="en">
<head>
<title><!-- Insert your title here --></title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#from').keyup(function(event) {
$('#to').text($('#from').val());
});
});
</script>
</head>
<body>
<textarea id="from" rows=10 cols=10></textarea>
<textarea id="to" rows=10 cols=10></textarea>
</body>
</html>
回答by Sumit Pandit
$(document).ready(function(){
$("#textbox1").blur(function(){$('#textbox2').val($('#textbox1').val()});
}
Action will perform on blur of textbox1.
操作将对 textbox1 的模糊执行。

