Home » Jquery » jquery – JavaScript get clipboard plain text with enter data on paste event (Cross browser)

jquery – JavaScript get clipboard plain text with enter data on paste event (Cross browser)

Posted by: admin February 22, 2020 Leave a comment

Questions:

How can a web application detect a paste event and retrieve the data to be pasted?

I would like to remove all HTML tags, CSS and other things except plain text and enter.

It will also work in all major browser like Google Chrome, Firefox, IE, Edge, Safari, Opera etc.

<div placeholder="Share Something ?" contenteditable="true" id="post"></div>

if (document.querySelector('#post[contenteditable]')) {
    document.querySelector('#post[contenteditable]').addEventListener("paste", function(e) {
      e.preventDefault();
      var text = e.clipboardData.getData("text");
      document.execCommand("insertHTML", false, text);
    });
}
How to&Answer:
$("#inputText").bind("paste", function(e){
    var pastedData = e.originalEvent.clipboardData.getData('text');
    var regex = /^[[email protected]]+$/;
  	if (regex.test(pastedData) !== true) {    		
    		alert("You can enter only plain text");
        setTimeout(function(){
        	$("#inputText").html('');
        },100)
    } else {
    		alert("Valid text");
    }
});
#inputText {
  border:1px solid #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div placeholder="Share Something ?" id="inputText" contenteditable="true"></div>

You can bind paste event on the input text box. For plain text, you have to use a regular expression to validate the text.