I want to use my button to add a line of text underneath whatever is already existing in the textarea
field. Sometimes it is populated, other times it is not (determined by the $Item["description"]
).
It works when I try it in a W3schools editor, so what am I missing? Is it something to do with the placement of a div inside the text area?
function addNewMessage() {
document.getElementById("container").innerHTML = "<p><em>Here is the new message!</em></p>";
}
<textarea name='short_description' id='short_desc' form='edit_item'>
<div id='container'>Foo bar</div>
</textarea>
CodePudding user response:
You cannot place other elements inside a <textarea>
. Use a contenteditable
div element instead.
function addNewMessage() {
document.getElementById("container").innerHTML = "<p><em>Here is the new message!</em></p>";
}
#container {
border: 1px solid black;
padding: 2px;
}
<div id="container" contenteditable></div>
<input type='button' class='inputbutton' value='Add New Message' onclick="addNewMessage()">
CodePudding user response:
The issue is because your HTML is invalid, and the way you're trying to update it in the JS is incorrect. The textarea
element can only contain text, not rendered HTML, so placing the <div id="container" />
element there will not work.
To do what you require, change the HTML so that the textarea
only contains text, then update your JS to retrieve the #short_desc
element and update its value
instead of its innerHTML
:
function addNewMessage() {
document.getElementById("short_desc").value = "Here is the new message! ";
}
textarea {
width: 400px;
height: 100px;
}
<textarea name="short_description" id="short_desc" form="edit_item">Foo bar </textarea>
<input type="button" value="Add New Message" onclick="addNewMessage()" />