Reputation: 10346
This is an age-old question, but I'm still having trouble with it. You see, I'm trying to paste some Excel data in a Text Area, but the silly browsers freeze for long periods of time when doing this, because of God-knows-what "smart" parsing they do. I can't get rid of that (file upload is out of the question, my boss wants me to paste rows from Excel in a Text Area).
The good news is that pasting in a standard textbox WORKS. But I can't force them to paste there. So I am trying to catch the paste event in the Text Area and then throw the text over to the textbox. Unfortunately, I stopped short at the pasting part. I can't paste the text via JS into the simple textbox.
So my question is: how do you paste a text, how do you invoke it via JS? There are some solutions which only work in IE, that's not good, of course ::- ).
Upvotes: 4
Views: 2320
Reputation: 1661
Simple.
var isIe = (navigator.userAgent.toLowerCase().indexOf("msie") != -1
|| navigator.userAgent.toLowerCase().indexOf("trident") != -1);
document.getElementById('textinput').addEventListener('paste', function(e) {
var text;
if (isIe) {
text = window.clipboardData.getData('Text')
} else {
text = e.clipboardData.getData('text/plain');
}
// Do whatever you want with the text
console.log(text);
//If you don't want the text pasted in the textarea
e.preventDefault();
});
<textarea id="textinput"></textarea>
If you want, you can even get rid of the textarea and do this more directly. I wrote a technical blog post explaining how we do copying and pasting at Lucidchart (where I work).
Upvotes: 6
Reputation: 3542
Try CodeMirror as alternate solution. Doesn't check it with copy&paste with huge/excel amount of data but maybe this help...
Upvotes: 0
Reputation: 659
Enable javascript Copy to Clipboard in Firefox or Mozilla: http://www.febooti.com/support/website-help/website-javascript-copy-clipboard.html
Upvotes: 0
Reputation: 98906
I can't paste the text via JS into the simple textbox
When you say “simple textbox”, do you mean <input type="text">
? If so, then I think setting its value
attribute to the text you’ve captured from the <textarea>
should work.
Upvotes: 0
Reputation: 33551
Sorry, didn't quite catch the idea. Can't you attach to thextarea's onpaste
event (at least I know IE has such event) and then simply set textarea's value to the pasted value?
pastedContent = window.clipboardData.getData("Text");
document.getElementById("yourtextarea").value = pastedContent;
EDIT: ok, it seems like this only works in IE and newer versions of FF, but it's not a cross-browser solution.
Upvotes: 1