Reputation: 710
I am trying to show whatever is typed/pasted/cut/deleted in one textarea in another textarea. But I'm having problem when backspace and delete is pressed. I'll probably have problem with deleting selections, cuting, pasting, undo, redo etc aswell. How can I best solve this problem? Code:
<html>
<head>
<title>Live Text Sync</title>
<meta charset="utf-8"/>
</head>
<body>
<textarea id="a"></textarea>
<textarea id="b"></textarea>
<script>
var a = document.getElementById("a");
var b = document.getElementById("b");
a.onkeydown = function(e) {
if(!e.ctrlKey) {
if (e.which >= 65) {//A
var letter = String.fromCharCode(e.which);
if (!e.shiftKey) letter = letter.toLowerCase();
b.value = b.value.substring(0, a.selectionStart) + letter + b.value.substring(a.selectionEnd);
} else if (e.which === 8) {//backspace
var text = b.value;
var till = a.selectionStart === 0 ? 0 : a.selectionStart - 1;
b.value = text.substring(0, till) + text.substring(a.selectionEnd);
} else if (e.which === 46) {//delete
var text = b.value;
var van = text.length < a.selectionEnd ? a.selectionEnd : a.selectionEnd + 1;
b.value = text.substring(0, a.selectionStart) + text.substring(van);
}
}
}
</script>
</body>
</html>
Upvotes: 1
Views: 902
Reputation: 1
The answer given by @fuyushimoya is very poor quality and does not work the way you intended. If you actually wanted to sync them, you would have to ensure the value gets updated on input in either textarea.
<html>
<head>
<title>Live Text Sync</title>
<meta charset="utf-8" />
</head>
<body>
<textarea id="a"></textarea>
<textarea id="b"></textarea>
<script>
var a = document.getElementById("a");
var b = document.getElementById("b");
a.oninput = function(e) {
b.value = a.value;
}
b.oninput = function(e) {
a.value = b.value;
}
</script>
</body>
</html>
Upvotes: 0
Reputation: 9813
Is there any reason not to use .value
to sync 2 textarea
s?
<html>
<head>
<title>Live Text Sync</title>
<meta charset="utf-8" />
</head>
<body>
<textarea id="a"></textarea>
<textarea id="b"></textarea>
<script>
var a = document.getElementById("a");
var b = document.getElementById("b");
a.oninput = function(e) {
b.value = a.value;
}
</script>
</body>
</html>
Upvotes: 3