views:

339

answers:

3

I have two text boxes t1 and t2 in an html page.

I'd like to copy t1 content to t2, using javascript on every keystroke done in t1.

+3  A: 

Using jquery this would look something like this:

$(function() { $(t1).keyup(function() { $(t2).val($(t1).val()) } })

Eimantas
where to write what is the syntax we need to use here
peter
in head or body part
peter
<head> <script type="text/javascript"> ...the code... </script></head>
Eimantas
actually it doesn't matter since the function will be hooked to keyup event after dom is ready.
Eimantas
Thanks Elimantas
peter
+3  A: 

Ol' school, since you added the "beginner" tag:

<input type="text" id="t1" onkeyup="document.getElementById('t2').value = this.value" />
<input type="text" id="t2" />

A more robust solution also uses the change event (for those who paste via mouse right-click), and doesn't inline the event handler logic:

<input type="text" id="t1" />
<input type="text" id="t2" />

<script>
var t1 = document.getElementById('t1');
t1.onkeyup = t1.onchange = function() {
    document.getElementById('t2').value = this.value;
};
</script>
Crescent Fresh
this is not unobtrusive. you should teach beginner to have good manners when coding html/js .)
Eimantas
@Eimantas: see my edit.
Crescent Fresh
+1  A: 

You could use this ugly thing:

<html>
<body>
  <textarea id="t1" onkeyup="document.getElementById("t2").value = this.value;"></textarea>
  <textarea id="t2"></textarea>
</body>
</html>
voyager