How to copy newline characters from HTML div to textarea in jQuery? - javascript

Consider the following HTML page fragment:
<div id='myDiv'>
Line 1.<br />
Line 2<br />
These are &ltspecial> characters & must be escaped !##><>
</div>
<input type='button' value='click' id='myButton' />
<textarea id='myTextArea'></textarea>
<script>
$(document).ready(function () {
$('#myButton').click(function () {
var text = $('#myDiv').text();
$('#myTextArea').val(text);
});
});
</script>
First, there is a div element with id myDiv. It contains some text similar to what might be retrieved form a SQL database at runtime in my production web site.
Next, there is a button and a textarea. I want the text in myDiv to appear in the textarea when the button is clicked.
However, using the code I provided, the line-breaks are stripped out. What can I do about this, taking into consideration that escaping special characters is absolutely non-negotiable?

Your code works great for me in both Firefox and Chrome: http://jsfiddle.net/jYjRc/
However, if you have a client that doesn't do what you want, replace <br>s with newline characters.
Edit: Tested in IE7 and the code breaks. So I updated the fiddle with my suggestion: http://jsfiddle.net/jYjRc/1/

Do your HTML like so:
<div id='myDiv'><pre>
Line 1.
Line 2
These are &ltspecial> characters & must be escaped !##><>
</pre></div>
And now .text() will return the text exactly as you specify it in the <pre> tag, even in IE.

Related

puppeteer escaping double quotes in style attribute

I'm using Google's puppeteer to read HTML, make some changes to it, and save it to a new HTML file.
Almost everything is working properly, except puppeteer is escaping double-quote characters (") as " inside the style attribute.
For example:
style='font-size:11.0pt;font-family:"Arial",sans-serif;
color:#D99594'
becomes:
style="font-size:11.0pt;font-family:"Arial",sans-serif;
color:#D99594"
This is affecting not only the output HTML, but some of the processing I'm doing within Puppeteer.
I believe I've ruled out encoding as an issue. Any ideas or fixes?
Thanks!
Problem
Functions like page.content() or similar functions that return HTML, will give you the current HTML representation of the DOM. However, this DOM representation of your HTML code might differ from your given HTML code. Therefore, this is expected behavior.
To name some examples:
Chrome will make <div/> into <div></div>.
Chrome will use double quotes for attributes: <div id='a'></div> becomes <div id="a"></div>
Chrome will make attributes lower case: <div ID="a"></div> becomes <div id="a"></div>
Chrome will try to fix your code: <div><span></div></span> becomes <div><span></span></div>
Try it yourself
To test it yourself you can use the following code. It will put some code into the DOM and then use innerHTML to check what the DOM actually looks like. Click on Run code snippet at the bottom and enter any code you want to test:
const el = document.querySelector("#domTester");
const output = document.querySelector('#output');
function showResult() {
const outerElement = document.createElement('div');
outerElement.innerHTML = el.value;
output.value = outerElement.innerHTML;
}
el.addEventListener('input', showResult);
showResult();
<p>
What you give to the browser:<br />
<input id="domTester" type="text" value="<div id='a " b'/>" style="width:100%" />
</p>
<p>
What the DOM will be rendered as:<br />
<input id="output" type="text" readonly="readonly" style="width:100%" />
</p>

How to write a code inside <pre> tag without apply the code

I have two places, the first is,<textarea></textarea> and used to write the code.
The second is, <pre></pre> and used to display the code.
The problem is, when write a code in the text area to display it in the second place, the code is applied and displayed as HTML element not just code as I want.
The wrong behavior:
The correct behavior (What I want):
The code:
<textarea id="inputCode" cols="50" rows="10"></textarea><br/>
<pre id="outputCode"></pre>
Using innerText to set the value of the second textarea will add the textual value only, not the HTML.
<pre id="code"></pre>
document.getElementById("code").innerText = "<input type='text' />";
Will insert in to the pre tags,
<input type='text' />
Example
JSFiddle

<br> is removed when I alert() the content of PRE tag

I want to show the content of this <pre> tag using alert():
<pre> This is the IRNIC Whois server v1.6.2.<br> Available on web at http://whois.nic.ir/<br> Find the terms and conditions of use on http://www.nic.ir/<br> <br> This server uses UTF-8 as the encoding for requests and responses.<br><br> NOTE: This output has been filtered.<br><br> Information related to 'shirzadi.ir'<br><br><br>domain: shirzadi.ir<br>ascii: shirzadi.ir<br>remarks: (Domain Holder) Ehsan Shirzadi<br>remarks: (Domain Holder Address) Ferdowsi Blv , Mahdi 13 ST, Mashhad, Khorasan razavi, IR<br>holder-c: es372-irnic<br>admin-c: es372-irnic<br>tech-c: to52-irnic<br>bill-c: to52-irnic<br>nserver: wres1.irpowerweb.com<br>nserver: wres2.irpowerweb.com<br>last-updated: 2014-01-16<br>expire-date: 2017-10-08<br>source: IRNIC # Filtered<br><br>nic-hdl: es372-irnic<br>person: Ehsan Shirzadi<br>e-mail: ehsan.shirzadi#gmail.com<br>address: Ferdowsi Blv , Mahdi 13 ST, Mashhad, Khorasan razavi, IR<br>phone: +985117688851<br>fax-no: +989155066372<br>source: IRNIC # Filtered<br><br>nic-hdl: to52-irnic<br>org: Fanavarie Etelaate Towseye Saman (Mihannic)<br>e-mail: sales#mihannic.com<br>source: IRNIC # Filtered<br><br></pre>
when I read this content using xx = $('pre').text() and then alert(xx), the is no <br> but when I hard code this content in a variable and alert() I can see them. What is the problem here? finally I want to split the contents by <br>
Try $('pre').html() instead of text(). This should preserve < br > as well as other tags / html entities.
Edit
For completeness, as gillesc said, < br > and other tags will be stripped in alert() (since it does not support inner html). Therefore combination of .html() and replace method is required. Newline can be replaced by \n. Full code would look like this:
xx = $('pre').html().replace(/<br>/g, "\n");
alert(xx);
text() will strip the tags out so use html() instead but alert doesn't support tags so you will need to convert your <br/> before sending it to laert
See this post on how to do just that.
HTML Tags in Javascript Alert() method
Using text() keeps only the inner text, not the HTML markup.
Use html() and eventually replace each captured <br /> by the JS new line character, like said here : How replace HTML <br> with newline character "\n"
Make Like This
<pre id="MyID">This is Test <br /> This is test</pre>
and javascript code
<script>
alert(document.getElementById('MyID').innerHTML);
</script>

Escape HTML tag in <textarea>

I have one <textarea> tag in my website where the user can put there HTML code and see its preview. My problem is when the user enter code below mention in my <textarea> my preview functionality getting fail :
<html>
<textarea>Some code to show</textarea>
</html>
So question is how can I escape this html code in my <textarea> tag as I know the problem is coming because </textarea> tag.
Any solution on this please.
Edit
Question is about using </textarea> within a textarea.
Problem visible here: http://jsfiddle.net/hrP6F/
EDIT: for your purpose this would do:
<textarea>
Outside Textarea
<textarea>Inside Textarea</textarea>
</textarea>
source: How can I embed a textarea inside of another textarea in HTML?
Or use contenteditable like someone already mentioned -> click
FIRST ANSWER: Im not sure I understand perfectly but still. You want to display the code inside text area somewhere else for instance?
You could do that on click like this (I reckon you are not statically putting nested text areas in html?):
HTML:
<textarea id="textarea" >Something code to show</textarea>
<button onclick="show()">show</button>
<div id="showArea"></div>
JS:
function show(){
var t = document.getElementById('textarea').value;
document.getElementById('showArea').innerHTML = t;
}
This is of course if what you want is to display html that is inside textarea. you could also put another textarea inside first one and it will work.
If you want the results to display dynamically you could use
<textarea id="textarea" onkeyup="show()">Something code to show</textarea>
This works even if you put your code (html and text area) inside text area - it displays it, I tested it
You can add a output div for preview purpose. Below is the jQuery script
HTML
<textarea placeholder="Enter your html"><b>test</b></textarea>
Run
<div class="op"></div>
JS
$('.run').click(function(){
$('.op').html($('textarea').val());
return false;
});
DEMO

special character is not coming in alert box as it it

I have one code
<input type="button" id="btnGetText" value="Get Text"/>
<div id="myDiv">
<p>First Lineα and text.</p>
<p>Second Line <b>Bolded</b></p>
</div>
If I am alerting the html of #myDiv is coming in alert but &alpha not coming.
If I am alerting &alpha its giving α
here is the fiddle attached
http://jsfiddle.net/getyoursuresh/hv2ed/
You are not alerting the original HTML. You are alerting a serialization of the DOM to HTML.
α and α are equivalent in HTML, so either are perfectly valid when designing a serialization algorithm. HTML 5 describes the algorithm browsers are supposed to use.
As described in the section starting "Escaping a string", non-breaking spaces should be serialized to character references while alphas are not.
If you want to work with your original HTML then you'll need to use XMLHttpRequest to refetch the original document from the server and then parse the raw text of the response yourself.
Edited:
Alpha character can be used directly in html although it has an html encoding, unlike the unbreakable space which has to remain in html encoding even after processing it because that character only exists in html encoding.

Categories