Write a newline in a textarea with Javascript [duplicate] - javascript

This question already has answers here:
Javascript Line Break Textarea
(6 answers)
Closed 4 years ago.
I am writing a little JS script which produces an output on multiple lines, and I want to display this output in a textarea with id message. I know that a textarea does not interpret html. Since the textarea is a form tag, I tried the following to display my result:
$("#message").val("test\\ntest"); writes test\ntest in the textarea
$("#message").val("test
test"); writes test
test in the textarea
But since it is also an open-close tag, I assumed that the .html() attribute was valid on it, and it seems to be, but when I do the following:
$("#message").html("test\\ntest");
$("#message").html("test
test");
it does not update anything visible in the textarea, but when I look into the console and inspect the element, I see the well formated text between the two tags.
The only way I was able to do it is the write directly the text in the textarea, like so:
<textarea id="message>test
test</textarea>
which produces a well formated output, but since I want my JS script to update it it is not relevant.
I read a lot of topics and suggestions, but none seems to answer to my specific question: Is there any way I can modify in Javascript the value of a textarea displaying text on multiple lines?
tl;dr
I tried the following (fill all the textareas before testing):
$("#button").click( function() {
$("#ta1").val("test\\ntest");
$("#ta2").val("test
test");
$("#ta3").html("test\\ntest");
$("#ta4").html("test
test");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Fill all the textareas before testing</p>
<button id="button">Test</button>
<p>Test 1 : </p>
<textarea id="ta1"></textarea></br>
<p>Test 2 : </p>
<textarea id="ta2"></textarea></br>
<p>Test 3 : </p>
<textarea id="ta3"></textarea></br>
<p>Test 4 : </p>
<textarea id="ta4"></textarea></br>
<p>Test 5 : </p>
<textarea id="ta5">test
test</textarea>
and none of thoses tests are allowing me to replace the textarea value with multiline text.
Do you have a solution ?

As JJJ correctly states in comments, just include \n in the value:
$("#button").click( function() {
$("#ta1").val("test\ntest");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Test</button>
<p>Test:</p>
<textarea id="ta1"></textarea>
Your attempts fail because:
"\\" is interpreted as a backslash in a string, then n is just a "n". There is no newline.
val will not interpret HTML.
same as the first case
This actually works - for the initial value. When <textarea> is initialised, its value is its content. After it is first edited, it's the value property that matters, and the content is not relevant any more. Which is why it works if you haven't edited the <textarea>, but not if you did.
The first case was closest to working, you just went overboard with backslashes.

Related

Why do I get this <br> element in a contenteditble div?

I have a div element that looks like this
<div id="test" contenteditable="true" style="height: 17px;">
</div>
When I do $("#test").html(), I'd expect to see an empty string returned, but in fact, it gives me <br>.
Why would there be a <br> even if I haven't put any there in the div?
Edit: Actually, in between the div tag, I have a Struts2 property tag which outputs a value but this value populated in the backend is empty so I was not expecting to see <br> there.
It's look like strange issue, As far my experience it can be due to these stuff
It may be html tags are not closed
You may have some browser extension which some time do these type weird stuff
so try to disable all extension and check all html tags also try in incognito mode after disable extension, I think it may help you for debugging this issue.
https://jsfiddle.net/47r6p89r/
There is space between <div ...> and </div>.
Also spaces will be detect by HTML but only one by one. The weird thing is that you got
<br>
as output I just got nothing as in the fiddle.
Here like in my fiddle you can detect if #test is empty if not you can see the result.
$(document).ready(function() {
if ($('#test').html() !== "")
$('#console').text($('#test').html());
else
$('#console').text('empty');
});

How to validate or wrap user inputted HTML to fix unclosed tags

I have text boxes in a form where users can input formatted text or raw HTML. It all works fine, however is a user doesn't close a tag (like a bold tag), then it ruins all HTML formatting after it (it all becomes bold).
Is there a way to either validate the user's input, automatically close tags, or somehow wrap the user input in an element to stop it leaking over?
You may try jquery-clean
$.htmlClean($myContent);
Is there a way to either validate the user's input, automatically close tags, or somehow wrap the user input in an element to stop it leaking over?
Yes: When the user is done editing the text area, you can parse what they've written using the browser, then get an HTML version of the parsed result from the browser:
var div = $("<div>");
div.html($("#the-textarea").val());
var html = div.html();
Live example — type an unclosed tag in and click the button:
$("input[type=button]").on("click", function() {
var div = $("<div>");
div.html($("#the-textarea").val());
var html = div.html();
$(document.body).append("<p>You wrote:</p><hr>" + html + "<hr>End of what you wrote.");
});
<p>Type something unclosed here:</p>
<textarea id="the-textarea" rows="5" cols="40"></textarea>
<br><input type="button" value="Click when ready">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Important Note: If you're going to store what they write and then display it to anyone else, there is no client-side solution, including the above, which is safe. Instead, you must use a server-side solution to "sanitize" the HTML you get from them, to remove (for instance) malicious content, etc. All the above does is help you get mostly-well-formed markup, not safe markup.
Even if you're just displaying it to them, it would still be best to sanitize it, since they can work around any client-side pre-processing you do.
You could try and use : http://ejohn.org/blog/pure-javascript-html-parser/ .
But if the user is entering the html by hand you could just check to have all tags closed properly. If not, just display an error message to the user.
You can create a jQuery element using the text and then get it's html, like so
Sample
<textarea>
<div>
<div>
<span>some content</span>
<span>some content
</div>
</textarea>
Script
alert($($('textarea').text()).html());
alert($($('textarea').text()).html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>
<div>
<div>
<span>some content</span>
<span>some content
</div>
</textarea>
The simple way to check if entered HTML is actually valid and parseable by browser is to let browser try it out itself using DOMParser. Then you could check if result is ok or not:
function checkHTML(html) {
var dom = new DOMParser().parseFromString(html, "text/xml");
return dom.documentElement.childNodes[0].nodeName !== 'parsererror';
}
$('button').click(function() {
var html = $('textarea').val();
var isValid = checkHTML(html);console.log(isValid)
$('div').html(isValid ? html : 'HTML is not valid!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea cols="80" rows="7"><div>Some HTML</textarea> <button style="vertical-align:top">Check</button>
<div></div>

Can't get text to line break with <br> after inserting with innerHTML

I'm relatively new to HTML, js, coming from Delphi. I have reviewed the following answers but they don't seem to work for me, or I am not understanding what they are saying:
Multi line print
.innerHTML <br> breaking
html <br> and innerHTML problem
Problem: all my text is printing in one line, rather than line breaking.
Below is the HTML source.
<!DOCTYPE HTML>
<html>
<head>
<title>Test Module</title>
</head>
<body >
<p id="demo"></p>
<button id="btnRPCTest" onclick="RPCTest()">Test RPC call</button>
<p id="RPCTarget">(RPC output here...)</p>
<script id="broker" src="scripts/rpcbroker.js" type="text/javascript"></script>
<script>
function RPCTest() {
var Div = document.getElementById("RPCTarget")
Broker_CallV("XUS INTRO MSG", []);
var text = Broker_ResultsDelim("<br />\n");
Div.innerHTML = text;
}
</script>
</body>
</html>
Above, the code makes a remote procedure call (RPC) to the server, and the results are put into a custom TStringList object that I created, that at it's core is an array of strings.
Below, is the code that gets back the results as a string, deliminated by the specified parameter ADelim.
function Broker_ResultsDelim(ADelim) {
return TStringList.GetTextDelim(RPCBrokerV.Results, ADelim);
}
Below, the array of strings should be concatenated into one long string, with contained line breaks.
GetTextDelim: function (Self, ADelim) {
return (Self.FData).join(ADelim) + ADelim;
},
When I run this code, and step through it with the Chrome developer console, I can type 'text' in the console, and the line breaks are correct.
> text
"
...............................................................
.................#.............................................
...###############.......##############..........########......
.################......################........####...####.....
.##.....####..........##....####.....###......##.......####....
.###....###...##............###......##......##................
..##....#######.............###.....###.....###................
.......###..##.............##########.......###....#########...
.......###.................###...............##........###.....
.......###.................###...............###......####.....
......###.................###.................####....###......
...###########........############.............##########......
......................................................###......
................................................########.......
...............................................................
<br />
"
But after the text gets inserted into the div, it is all on one line. I can't demonstrate that here, because when I copy the text (which appears on the screen to be all one line), and paste it into this question on StackOverflow, suddenly is is formatted correctly, with line breaks.
This makes me think that the text does contain the line break BR codes , but they are being ignored in the div.
I would think that this should be an easy question for someone knowledgeable in HTML, but it's got me scratching my head in confusion. Thanks in advance for the help.
Kevin
I'm going to ignore how you're generating the text. I'm going to assume that it is returned in a format like this, where there are actual line breaks ("\n") at the end of every line:
var code =
"\
...............................................................\
.................#.............................................\
...###############.......##############..........########......\
.################......################........####...####.....\
.##.....####..........##....####.....###......##.......####....\
.###....###...##............###......##......##................\
..##....#######.............###.....###.....###................\
.......###..##.............##########.......###....#########...\
.......###.................###...............##........###.....\
.......###.................###...............###......####.....\
......###.................###.................####....###......\
...###########........############.............##########......\
......................................................###......\
................................................########.......\
...............................................................\
"
I used \ to concatenate the strings, but a "\n" works as well. Now, all you have to do is:
CSS
html {
font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
/* so that the text is monospace and lines up correctly */
}
HTML
<div id="holder">
</div>
JavaScript
$("#holder").append(code.split("\n").join("<br>"));
// or, without jQuery
document.getElementById("holder").innerHTML = code.split("\n").join("<br>");
fiddle
Your second option is to, as Hardy mentioned in the comments, use a <pre> tag. This will maintain the formatting that you give it, so all you would have to do is insert code into a <pre> tag.
Use <pre> tag in your javascript like:
<script>
function RPCTest() {
var Div = document.getElementById("RPCTarget")
Broker_CallV("XUS INTRO MSG", []);
var text = Broker_ResultsDelim("\n");
Div.innerHTML = "<pre>" + text + "</pre>";
}
</script>
you only have one
<br/>
tag in your output. Notice that it is at the end of the console output you need to replace \n line breaks with
<br />
or replace
<p id="RPCTarget">(RPC output here...)</p>
with
<pre id="RPCTarget">(RPC output here...)</pre>
and remove the trailing
<br />

EpicEditor text showing as instead of space

Not sure if this is an actual problem per se but I'm using Epic Editor to input and save markdown in my GAE application (webpy with mako as the templating engine).
I've got a hidden input element in the form which gets populated by the EpicEditor's content when I submit the form but all the white spaces are replaced by . Is this an intended feature? If I check the same code on the EpicEditor site, it clearly returns spaces instead of so what's different about mine?
<form>
<!-- form elements -->
<input id="content" name="content" type="hidden" value></input>
<div id="epiceditor"></div>
<button type="submit" name="submit" id="submit">submit</button>
</form>
<script type="text/javascript">
$('button#submit').click(function(){
var content = editor.getElement('editor').body.innerHTML; //all the spaces are returned as and breaks are <br>
$('input#content').html(content);
});
</script>
NOTE: I want to save my content as markdown in a TextProperty field my data store and generate the html tags when I retrieve it using marked.js
I'm the creator of EpicEditor. You shouldn't be getting the innerHTML. EpicEditor does nothing to the innerHTML as you write. The text and code you are seeing will be different between all the browsers and it's how contenteditable fields work. For example, some browsers insert UTF-8 characters for spaces some &nbsp.
EpicEditor gives you methods to normalize the text tho. You shouldn't ever be trying to parse the text manually.
$('button#submit').click(function(){
var content = editor.exportFile();
$('input#content').html(content);
});
More details on exportFile: http://epiceditor.com/#exportfilefilenametype
P.S. You don't need to do input#content. Thats the same as just #content :)
You can do this if you dont find out why:
<script type="text/javascript">
$('button#submit').click(function(){
var content = editor.getElement('editor').body.innerHTML;
content = content.replace(" ", " ");
$('input#content').html(content);
});
</script>
[EDIT: solved]
I shouldn't be using innerHTML, but innerText instead.
I figured out that Epic Editor uses on all spaces proceeding the first one. This is a feature, presumably.
However that wasn't the problem. ALL the spaces were being converted to , eventually, I realised it occurs when Epic Editor loads the autosaved content from localStorage.
I'm now loading content from my backend every time instead of autosaving. Not optimal, but solves it.

Javascript form innerHTML

i have an issue with innerHTML and getElementsById(); method but I am not sure if these two methods are the root of the issues i have.
here goes my code :
<script type="text/javascript">
function clearTextField(){
document.getElementsById("commentText").value = "";
};
function sendComment(){
var commentaire = document.getElementById("commentText").value;
var htmlPresent = document.getElementById("posted");
htmlPresent.innerHTML = commentaire;
clearTextField();
};
</script>
and my HTML code goes like this:
<!doctype html>
<html>
<head></head>
<body>
<p id="posted">
Text to replaced when user click Send a comment button
</p>
<form>
<textarea id="commentText" type="text" name="comment" rows="10" cols="40"></textarea>
<button id="send" onclick="sendComment()">Send a comment</button>
</form>
</body>
</html>
So theorically, this code would get the user input from the textarea and replace the text in between the <p> markups. It actually works for half a second : I see the text rapidly change to what user have put in the textarea, the text between the <p> markup is replaced by user input from <textarea> and it goes immediately back to the original text.
Afterward, when I check the source code, html code hasn't changed one bit, given the html should have been replaced by whatever user input from the textarea.
I have tried three different broswer, I also have tried with getElementByTagName(); method without success.
Do I miss something ? My code seems legit and clean, but something is escaping my grasp.
What I wanted out of this code is to replace HTML code between a given markup (like <p>) by the user input in the textarea, but it only replace it for a few milliseconds and return to original html.
Any help would be appreciated.
EDIT : I want to add text to the html page. changing the text visible on the page. not necessarily in the source. . .
There is no document.getElementsById, however there is a document.getElementById. This is probably the source of your problem.
I don't think there is any document.getElementsById function. It should be document.getElementById.
"To set or get the text value of input or textarea elements, use the .val() method."
Check out the jquery site... http://api.jquery.com/val/

Categories

Resources