Ismir Wumpe
Ismir Wumpe

Reputation: 65

JavaScript textarea

im new to js and have issues with following. I want the content of a html text input field to be displayed within a textarea via button click. I tried this:

.
.
function addText()
{
   var contentOfTxtField = document.getElementById("txtToGet").value;
   document.getElementById("idOfTheTextarea").innerHTML = contentOfTxtField;
}
.
.

Then I call my function in the onlick event of a button:

<button onclick="addText()">Add</button><br>

My problem is that the text shortly appears in the textarea but immediately disappears. Same for the entered text of the input text field. Any hints for me? Thk u

Upvotes: 0

Views: 62

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

Try to replace :

document.getElementById("idOfTheTextarea").innerHTML = contentOfTxtField;

By :

document.getElementById("idOfTheTextarea").textContent= contentOfTxtField;

NOTE : make sure that you're adding type='button' to the button since button tag act like submit by default.

Hope this helps.


Snippet

function addText()
{
   var contentOfTxtField = document.getElementById("txtToGet").value;
   document.getElementById("idOfTheTextarea").textContent = contentOfTxtField;
}
<input type="text" value='example value' id="txtToGet"/>
<br>
<button type="button" onclick="addText()">Add</button>
<br>
<textarea id='idOfTheTextarea'></textarea>

Upvotes: 2

epascarello
epascarello

Reputation: 207501

Sounds like the form is submitting, cancel the click event

<button onclick="addText(); return false;">Add</button><br>

Upvotes: 1

Related Questions