简体   繁体   English

当用户在文本框中键入值时,在另一个文本框中显示一个文本框值

[英]Showing one text box value in another text box while user type the value to the text box

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? 当用户在文本框中键入值时,有没有办法从一个文本框中获取值并使用jQuery动态添加到另一个文本框? can someone please explain the method if there is any such thing? 如果有这样的事情,请有人解释一下这个方法吗?

regrds, Rangana regangds,Rangana

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 keyup event handler on the first input . 首先,我们在第一个input上附加一个keyup事件处理程序。 This means that whenever somebody types something into the first input , the function inside the keyup() function is called. 这意味着只要有人在第一个input ,就会调用keyup()函数内的函数。 Then we copy over the value of the first input into the second input , with the val() function. 然后我们使用val()函数将第一个input的值复制到第二个input That's it! 而已!

$('#textbox1').keypress(function(event) {
    $('#textbox2').val($('#textbox1').val() + String.fromCharCode(event.keyCode));
}); 

This will ensure that textbox2 always matches the value of textbox1 . 这将确保textbox2永远的价值相匹配textbox1

Note: You can use the keyup event as others have suggested but there will be a slight lag possibly. 注意:您可以像其他人建议的那样使用keyup事件,但可能会有轻微的延迟。 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 keyup since keypress triggers before the keyup event even happens. 测试他们两个并按住一个键或键入真正快,你会使用注意到一个显著滞后keyup因为keypress触发前的keyup事件发生连。

<!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>
$(document).ready(function(){
    $("#textbox1").blur(function(){$('#textbox2').val($('#textbox1').val()});
}

Action will perform on blur of textbox1. 动作将对textbox1的模糊执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM