Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript how to paste "as plain text" in multiple fields or elements

I try to paste text into multiple fields, but the formatting is only cleared on the first element, not the second etc.

I found this question https://stackoverflow.com/a/12028136/3955607 which works fine, but again, on multiple elements it doesnt work.

So I got this HTML

<div style="color:red">Some <em>rich</em> <span style="font-size:2em">HTML</span></div>
<br />
<div style="border:1px solid red" contenteditable></div>
<br />
<div style="border:1px solid red" contenteditable></div>

and this javascript:

document.querySelector("div[contenteditable]").addEventListener("paste", function(e) {
   e.preventDefault();
   var text = e.clipboardData.getData("text/plain");
   document.execCommand("insertHTML", false, text);
});

I have this fiddle http://jsfiddle.net/tdjuc8es/

just copy and paste the Some rich HTML- text and see what happens

Someone who can help me out?

like image 541
ST80 Avatar asked Dec 11 '14 12:12

ST80


2 Answers

document.querySelector yields one element. You want to use document.querySelectorAll to get all matching elements, and then iterate over that collection.

var editors = document.querySelectorAll('div[contenteditable]');
for(var i = 0, l = editors.length; i < l; i++) {
   editors[i].addEventListener('paste', myCustomPasteFunction);
}

Fiddle

like image 68
David Hedlund Avatar answered Sep 22 '22 06:09

David Hedlund


If you're used to jQuery, you might think that document.querySelector() fulfils the same kind of function; however, it only returns the first element that matches the selector; instead you should have used document.querySelectorAll() and then used iteration to add your event handlers.

Since you've tagged it as jquery, you could also consider this:

$("div[contenteditable]").on("paste", function(e) {
   e.preventDefault();
   var text = e.originalEvent.clipboardData.getData("text/plain");
   document.execCommand("insertHTML", false, text);
});
div[contenteditable] {
    height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="color:blue">Some <em>rich</em> <span style="font-size:2em">HTML</span></div>
<br />
<div style="border:1px solid red" contenteditable></div>
<br />
<div style="border:1px solid red" contenteditable></div>

I'm using e.originalEvent here because the one that jQuery passes you in the event handler is a wrapper object.

like image 20
Ja͢ck Avatar answered Sep 18 '22 06:09

Ja͢ck