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?
regrds, Rangana
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?
regrds, Rangana
Share Improve this question edited Aug 29, 2010 at 6:02 Yi Jiang 50.1k16 gold badges138 silver badges136 bronze badges asked Aug 29, 2010 at 5:42 Rangana SampathRangana Sampath 1,4574 gold badges33 silver badges58 bronze badges 1- possible duplicate of Jquery: Mirror one text input to another – Felix Kling Commented Aug 29, 2010 at 7:53
4 Answers
Reset to default 13You mean something like 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
. 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 input
into the second input
, with the val()
function. 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
.
Note: You can use the keyup
event 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 keyup
since keypress
triggers before the keyup
event even happens.
<!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.