Home : Internet : JavaScript : Textarea Append / Replace

Add Text to a Textarea or Text Field

This page shows you to how to add (append) or replace text in a text area or text field. In the example below, the new text is entered in the left text area and added to the one on the right. We will also look at other options for acquiring the new text.

Add to Existing Text
Replace Existing Text


Step 1 - Create Text Area(s)

Use the following code to create the form and text areas. Modify the layout and names to suit your needs (but remember to change the function code as well if you do).

<form name="myform">
<table border="0" cellspacing="0" cellpadding="5"><tr>
<td><textarea name="inputtext"></textarea></td>
<input type="radio" name="placement" value="append" checked> Add to Existing Text<br>
<td><p><input type="radio" name="placement" value="replace"> Replace Existing Text<br>
<input type="button" value="Add New Text" onClick="addtext();"></p>
</td>
<td><textarea name="outputtext"></textarea></td>
</tr></table>
</form>

Step 2 - Create Function

Insert the following code into the page head:

<script language="javascript" type="text/javascript">
function addtext() {
	var newtext = document.myform.inputtext.value;
	if (document.myform.placement[1].checked) {
		document.myform.outputtext.value = "";
		}
	document.myform.outputtext.value += newtext;
}
</script>

More Options


To acquire the new text from something other than a text field, modify the newtext variable. For example:

// Pre-defined text:
var newtext = "This is the new text";
// Drop-Menu:
var newtext = myform.mymenu.options[myform.mymenu.selectedIndex].value;
// Prompt:
var newtext = prompt('Enter New Text Here:', '');

If you don't need to ask the user whether to replace or append the text, use the following simplified function:

<script language="javascript" type="text/javascript">
function addtext() {
	var newtext = document.myform.inputtext.value;
	document.myform.outputtext.value += newtext;
}
</script>

This example appends the new text to the existing text. To replace the existing text instead, remove the "+" sign.