Using JavaScript To Select Textarea Text

1st July 2008 - 2 minutes read time

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

  1. <form><textarea name="textarea1" id="textarea1" rows="5" cols="40" wrap="off">This is some
  2. long content.
  3. This is some long content.
  4. This is some long content.
  5. This is some long content.
  6. </textarea>
  7. <br />
  8. <input type="button" value="Select text" onclick="selectText('textarea1')">
  9. </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.

  1. function selectText(id){
  2. var id = document.getElementById(id);
  3. id.focus();
  5. }

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.