Simulate paste into Textarea with javascript - javascript

When pasting data from the clipboard into an html textarea, it does some pretty cool parsing to make the paste look close to what was copied as far as newlines go.
For example, I have the following html on a page that I select (everything highlights in blue) and then I copy it:
Hello
<br>
<br>
<br>
<div>more</div>
<div>last</div>
So to be clear, what I am copying is what the output of this jsfiddle looks like.
Now when I paste this magical, copied text into a text area, I see exactly what I would expect: "Hello", empty line, empty line, empty line, "more", "last". Cool! Then when I use jQuery's .val() on the textarea, I get "Hello\n\n\nmore\nlast". Super cool. It took the br's and div's and was able to infer the correct newlines from it.
Now...
What I am trying to do it programmatically take the same data I copied earlier and set it as the textarea's value as if it were pasted.
Here is what I have tried...
So, say the stuff I copied earlier was wrapped in a <div id="parent">...</div>.
var parent = $("#parent");
var textarea = $("#theTextArea");
// Set the value of the text area to be the html of the thing I care about
textarea.val(parent.html());
Now I know this isn't the same as a copy-paste, but I was hoping it would take care of me and do what I wanted. It doesn't. The textarea gets filled with Hello<br><br><br><div>more</div><div>last</div>. The html that was once invisible is now stringified and made part of the text.
Obviously I did this wrong. .html() returns, of course, the string of html. But is there something I could call on parent that would give me the text with all inferred linebreaks?. I have tried calling parent.text(), but this only gives Hellomorelast (no line breaks).
A few notes that could help with an answer: I am using Angular, so I have access to all their goodies and jQuery.

Edit:
Solution
It is not nice but you can try to replace html tags with line breaks '\n' or do some line breaks in the html file and get the content with text().
var parent1 = $("#paren1");
var textarea1 = $("#theTextArea1");
var parent2 = $("#paren2");
var textarea2 = $("#theTextArea2");
// Set the value of the text area to be the html of the thing I care about
var text = parent1.html();
text = text.replace(new RegExp("<br>", 'g'),"\n");
text = text.replace(new RegExp("<div>", 'g'),"");
text = text.replace(new RegExp("</div>", 'g'),"\n");
textarea1.val(text);
textarea2.val(parent2.text());
JSFiddle

Related

Textarea.value doesn't manipulate the HTML

Setting the value of the textarea, won't be reflected in the HTML.
For instance,
If you have <textarea></textarea> in your HTML, and set its value to 'Hello' the HTML will remain unchanged and not <textarea>Hello</textarea>
I think this is what you want, use this to your w3schools example
<script>
function myFunction() {
var x = document.getElementById("myTextarea").value;
document.getElementById("demo").innerHTML = x;
}
myTextarea.onkeyup=()=>myTextarea.innerText=myTextarea.value;
</script>
You seem to be working off some misconceptions. I take it you're expecting that line breaks in the text area will be reflected as line breaks in a paragraph if you insert it as the HTML of the paragraph. In HTML, all whitespace is collapsed into spaces, and line breaks in HTML source do not normally translate to breaks in HTML text flows. If you do want newlines to work in HTML, use a <pre></pre> element instead. Otherwise you'll need to convert newlines to <br> elements.
There's also the white-space CSS style that can change the way that whitespace is rendered.

Javascript find and higlight text between [quote][/quote] within textarea

I have this HTML code with pre-written message. My goal is to highlight text between [quote] [/quote] in a yellow background once I focus/click on the text area.
<textarea>
This is a test message.
[quote]Wise man said he is wise.[/quote] There could be more quotes too:
[quote]this is second quote [/quote]
He is correct.
</textarea>
Is it possible to do it with pure Javascript? I think it should be something like:
textarea onfocus="function()">
find text between [quote][/quote]
apply yellow background to found text: background Color='#ffc'
....
(and if there is no [quote] [/quote] found then it should do nothing, ie. no warnings).
Since you cannot do that using <textatea> i'd suggest to take a look at
<div contenteditable>
</div>
here's an example:
var area = document.getElementById("area");
var text = area.innerHTML;
area.innerHTML = text.replace(/\[\s*quote.*\](.*)[^[]*\[\s*\/quote.*\]/ig, "<span>$1</span>");
[contenteditable]{
white-space:pre-wrap;
}
[contenteditable] span{
background:#ffc;
}
<div id="area" contenteditable>
This is a test message.
[quote]Wise man said he is wise.[/quote] There could be more quotes too:
[quote]this is second quote [/quote]
He is correct.
</div>
Otherwise, since you cannot treat HTML elements inside a textarea like actual HTML elements in order to highlight them → you should create an in-memory element with the same size (font-size etc) of your textarea, do the above, calculate the positions of the generated span elements, than apply some higlight overlays over the respective positions over your textarea, take care that they "follow-up" if the window resizes... and the story goes...
Here's a jQuery plugin to achieve the above-mentioned:
http://mistic100.github.io/jquery-highlighttextarea/
Currently I'm investigating two approaches: Highlight Text Inside a Textarea, which describes how this plugin is done: https://github.com/lonekorean/highlight-within-textarea
And syntax higlighter for MediaWiki: source, description of approach.
Both of them use additional element behind textarea with the same font and positioning to show background colors. Textarea background is made transparent. Then on edit and scroll you sync contents and scroll between textarea and element behind.
Here is my simplified code for it: https://codepen.io/bunyk-1472854887/full/RLJbNq/
Core logic of the highlighter is like this (some details skipped):
textarea.addEventListener('keyup', textUpdate);
textarea.addEventListener('scroll', scrollUpdate);
function textUpdate() {
var html = html_escape(textarea.value);
enter code here
html = html.replace(/\[quote\](.*?)\[\/quote\]/g, '[quote]<span class="quote">$1</span>[/quote]');
background.innerHTML = html;
}
function scrollUpdate() {
background.scrollTop = textarea.scrollTop;
};

Escaped characters in text area but not in list

I had some help on here to create this:
http://jsfiddle.net/spadez/ZTuDJ/38/
My problem comes from the fact that html is stripped out when putting the value of the responsibility field into the text area, but when adding it to the list it still has the HTML on. That means that if someone types in this:
<b>Testing</b>
When I type this in, I get this in the text area when it is stripped:
Testing
But in the list it still has the html tags so it looks like this:
Testing
This is my code which puts it in the text are and the list:
$('#responsibilities').text($("<div>" + eachline + "</div>").text() ).before("<li>"+lines+"</li>");
My question: How do I put the same stripped value which goes into the text area also into the list.
$('#responsibilities').text($("<div>" + eachline + "</div>").text()).before("<li>"+$("<p>"+lines+"</p>").text()+"</li>");
Demo ---> http://jsfiddle.net/ZTuDJ/40/

turn <br> into line breaks using javascript (not php)

I need to extract the text from a div with paragraphs and spans and other things and put it into a textarea. I need to load just the text, not the HTML.
For that, I can use:
loadtext = $('#mydiv').text();
However, I DO need to retain the line breaks.
For that, I'm doing:
loadtext = $('#mydiv').text().replace(/<br>/gm, '\r\n');
But it doesn't seem to be working, because when I load that text into a textarea, it's all flat with no line breaks. Am I doing something wrong?
$('#mydiv').text() has already been stripped of all HTML, including<br> elements, so this will not work. You need to modify the HTML of the #mydiv element and replace all <br/> elements, then retrieve the text.
$('#mydiv').find('br').each(function(){
$(this).after("\n")
.remove();
});
var loadtext = $("#mydiv").text();
An alternate solution is to use an intermediate element that's never added to the document.
var html = $('#mydiv').html(); // e.g. '<p>line 1</p><br><br><p>line 2</p>'
var text = $('<div>').html(html.replace(/<br\/?>/g, '\n')).text();
/* text =
"line 1
line 2"
*/
$('#mytextarea').text(text);
This supports <br> (HTML) and <br/>(XHTML).

Need Solution on NicEdit Insert HTML text into Instance

i am using this function to insert text into NicEdit,
function insertAtCursor(editor, value){
var editor = nicEditors.findEditor(editor);
var range = editor.getRng();
var editorField = editor.selElm();
editorField.nodeValue = editorField.nodeValue.substring(0, range.startOffset) +
value +
editorField.nodeValue.substring(range.endOffset, editorField.nodeValue.length);}
This code works fine for simple text but when i pass HTML content into it, it does not render the HTML output in div instead it dumps the HTML code as it is into the Instance Div.
Example:
<div class="one">Some text here</div>
This must show in the Instance as "Some text here"
and remaining code hidden in source code.
Can any one give me a solution to fix this problem?
After working whole night and trying different solutions I had finally got it working! :)
In case any one wants to know solution for this, I had to add a Replace function
replace()
for the content and made it support HTML.
See my answer HERE. It's a plugin I created to insert html at the cursor position.

Categories