I have the following code where I am copying the following data:
ABC123
DEF123
HIJ123
and pasting it into the text area. So the cursor is just after the HIJ123
after pasting the code as shown below:
Now let’s say I introduce a new line after ABC123 as shown below:
And my cursor is on the line after ABC123 and then I try to past these 3 records again on that line, it is getting messed up as shown below:
Why it is not getting pasted where it should be and it’s getting messed up ?
let element = document.getElementById("post-text");
element.addEventListener('paste', (e) => {
e.preventDefault();
console.log(event.clipboardData);
element.value += (event.clipboardData || window.clipboardData).getData("text").trim()
});
document.getElementById('post-button').addEventListener('click', function() {
var lines = $('#post-text').val().split('n'); //gives all lines
///var lines = element.split('n');//gives all lines
//To paste
/*
ABC123
DEF123
HIJ123
*/
console.log(lines);
console.log(lines.length);
var firstLine = lines[0];
console.log(firstLine);
var secondLine = lines[1];
console.log(secondLine);
for (i = 0; i < lines.length; i++) {
$("#phrase").append("<div>" + lines[i] + "</div>")
}
});
#case-stack p {
white-space: pre-wrap; /* <-- THIS PRESERVES THE LINE BREAKS */
}
textarea {
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required></textarea><br>
<input type="button" id="post-button" value="Post!">
<div id="phrase"></div>
2
Answers
add event listener on paste
You can just remove the entire ‘paste’ event listener and let the default behaviour do its thing.
See demo below