I am trying to handle the paste event and trying to convert rich text into plain text, I have a content editable (dynamically created) div inside a container with id main
$("#main").on("paste","div",function(event){
event.preventDefault();
var clipboarddata = event.clipboardData ||window.clipboardData || event.originalEvent.clipboardData;
var onlytext = clipboarddata.getData('text/plain');
document.execCommand("insertHTML", false, onlytext);
});
Uncaught TypeError: Cannot read property 'getData' of undefined
I think event.clipboarddata
is not working, my browser supports clipboard API. i am copying the text and pasting it into div. So clipboard should have some value
Can someone explain why I clipboardData
is undefined
For latest browser Chrome below line will work.
var clipboarddata = window.event.clipboardData.getData('text');
$(document).ready(function(){
$("#main").on("paste",function(event){
event.preventDefault();
var clipboarddata = window.event.clipboardData.getData('text');
console.log("paste value" + clipboarddata);
$('#pasteData').text(clipboarddata);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="main" name="first_name" value="" maxlength="100" />
<div>paste value : <span id="pasteData"><span></div>
NOTE: This is WHY you are getting the error. Fixing the bug is a different matter and one that would need more information from you.
The reason you are getting the error is because when you use OR operators on variable assignment, it will always assign the value of the last one, even if it is null
, false
, or undefined
.
Basically, it goes like this
if (event.clipboardData != null/false/undefined) { //ignore the incorrectness of the truncation
var clipboarddata = event.clipboardData;
} else if (window.clipboardData != null/false/undefined) {
var clipboarddata = window.clipboardData;
} else { //default to the last option even if it is null/false/undefined
var clipboarddata = event.originalEvent.clipboardData;
}
So since all three are undefined
, you get the value of event.originalEvent.clipboardData
which is undefined
assigned to the variable. Hence the error on the next line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With