Pietro Pietro -4 years ago 139
Javascript Question

Add text to a textarea with Javascript

again I got a problem with Javascript, but this time is something more complex.

I'm trying to make a little Javascript text editor, basically it's an experiment, a test and the thing should be easy, I have a

html element, and a
html element, and both of them change, as the user write on a
<input type="text" />
element and a
Now, everything work fine, but there is a problem, for make a space between lines, the user can't just press enter, but course need to use the
<br />
html tag.
So my idea was to make a little button that allows the user to add this tag by pressing that button.
And Javascript just make a variable of the actual text, save it and add at the end of it the
<br />
the result should be the text written by the user plus the break html tag.
And this work, if the textarea is empty and if you have never written something on it, it work and work even 10 or 20 times, but if you write something on it, it just stop working, even if you delete all the text.
I can figure out what's the problem in the code below, please help me.

<title>Text editor</title>
<meta charset="utf-8" />
<link href="https://fonts.googleapis.com/css?family=Roboto|Roboto+Slab" rel="stylesheet">
.title {
font-family: roboto;
text-align: center;
.text {
font-family: roboto slab;
text-align: justify;
margin-bottom: 40px;
.container {
width: 80%;
.textarea {
width: 100%;
height: 30em;
text-indent: 0.5em;
.title_box {
margin: 10px;
width: 20em;
padding: 10px;
font-size: 1em;
<div class="container">
<h1 class="title" id="title_space">Title of the page</h1>
<p class="text" id="text_space">Content of the page.</p>
<hr />
<center><input type="text" class="title_box" placeholder="Title" id="title_box" /></center>
<textarea class="textarea" id="text_box"></textarea>
<input type="submit" value="Save" onclick="saveText()" />
<input type="submit" value="br" onclick="br()" />

function saveText(){
var title = document.getElementById("title_box").value;
var text = document.getElementById("text_box").value;

document.getElementById("title_space").innerHTML = title;
document.getElementById("text_space").innerHTML = text;

function br(){
var actualtext = document.getElementById("text_box").value;
var processedtext = actualtext + "<br />";
document.getElementById("text_box").innerHTML = processedtext;


Thank's for you time, and sorry for my horrible english.

Answer Source

When you're updating the text area, instead of:

document.getElementById("text_box").innerHTML = processedtext;


document.getElementById("text_box").value = processedtext;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download