Using JavaScript To Select Textarea Text

This is a simple trick that will allow users to select the contents of a text area. First we need a text area.

<form><textarea name="textarea1" id="textarea1" rows="5" cols="40" wrap="off">This is some
long content.
This is some long content.
This is some long content.
This is some long content.
</textarea>
<br />
<input type="button" value="Select text" onclick="selectText('textarea1')">
</form>

This form also includes a button with an on click event that runs a function. This function takes a single parameter as the name of the element. It then sets the focus to this element and then selects all of the text therein.

function selectText(id){
 var id = document.getElementById(id);
 id.focus();
 id.select();
}

Why is this useful? Well lets say you had a form or a quiz that produced and answer, and you wanted people to post their answer on their blogs, which then linked back to your quiz. This would allow users to select the contents of a text area without having to select it themselves.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
8 + 4 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.