W3cubDocs

/Web APIs

HTMLTextAreaElement

The HTMLTextAreaElement interface provides special properties and methods for manipulating the layout and presentation of <textarea> elements.

EventTarget Node Element HTMLElement HTMLTextAreaElement

Instance properties

accessKey string: Returns / Sets the element's accesskey attribute.
autocapitalize Experimental string: Returns / Sets the element's capitalization behavior for user input. Valid values are: none, off, characters, words, sentences.
autocomplete Experimental
autofocus boolean: Returns / Sets the element's autofocus attribute, indicating that the control should have input focus when the page loads
cols unsigned long: Returns / Sets the element's cols attribute, indicating the visible width of the text area.
defaultValue string: Returns / Sets the control's default value, which behaves like the Node.textContent property.
disabled boolean: Returns / Sets the element's disabled attribute, indicating that the control is not available for interaction.
form Read only object: Returns a reference to the parent form element. If this element is not contained in a form element, it can be the id attribute of any <form> element in the same document or the value null.
inputMode Experimental
maxLength long: Returns / Sets the element's maxlength attribute, indicating the maximum number of characters the user can enter. This constraint is evaluated only when the value changes.
minLength long: Returns / Sets the element's minlength attribute, indicating the minimum number of characters the user can enter. This constraint is evaluated only when the value changes.
name string: Returns / Sets the element's name attribute, containing the name of the control.
placeholder string: Returns / Sets the element's placeholder attribute, containing a hint to the user about what to enter in the control.
readOnly boolean: Returns / Sets the element's readonly attribute, indicating that the user cannot modify the value of the control.
required boolean: Returns / Sets the element's required) attribute, indicating that the user must specify a value before submitting the form.
rows unsigned long: Returns / Sets the element's forward" if selection was performed in the start-to-end direction of the current locale, or "backward" for the opposite direction. This can also be "none" if the direction is unknown.
selectionEnd unsigned long: Returns / Sets the index of the end of selected text. If no text is selected, contains the index of the character that follows the input cursor. On being set, the control behaves as if setSelectionRange() had been called with this as the second argument, and selectionStart as the first argument.
selectionStart unsigned long: Returns / Sets the index of the beginning of selected text. If no text is selected, contains the index of the character that follows the input cursor. On being set, the control behaves as if setSelectionRange() had been called with this as the first argument, and selectionEnd as the second argument.
tabIndex long: Returns / Sets the position of the element in the tabbing navigation order for the current document.
textLength Read only long: Returns the code point length of the control's value. Same as reading value.length
type Read only string: Returns the string textarea.
validationMessage Read only string: Returns a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation (willValidate is false), or it satisfies its constraints.
validity Read only ValidityState object: Returns the validity states that this element is in.
value string: Returns / Sets the raw value contained in the control.
willValidate Read only

boolean: Returns whether the element is a candidate for constraint validation. false if any conditions bar it from constraint validation, including its readOnly or disabled property is true.

wrap string: Returns / Sets the wrap HTML attribute, indicating how the control wraps text.
HTMLTextAreaElement.labels Read only NodeList: Returns a list of label elements associated with this element.

The two properties tabIndex and accessKey are inherited from HTMLElement.

Instance methods

blur() Removes focus from the control; keystrokes will subsequently go nowhere.
focus() Gives focus to the control; keystrokes will subsequently go to this element.
select() Selects the contents of the control.
setRangeText() Replaces a range of text in the element with new text.
setSelectionRange() Selects a range of text in the element (but does not focus it).
checkValidity() Returns false if the element is a candidate for constraint validation, and it does not satisfy its constraints. In this case, it also fires a cancelable invalid event at the control. It returns true if the control is not a candidate for constraint validation, or if it satisfies its constraints.
reportValidity()

This method reports the problems with the constraints on the element, if any, to the user. If there are problems, it fires a cancelable invalid event at the element, and returns false; if there are no problems, it returns true.

setCustomValidity(DOMstring) Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate.

The two methods blur() and focus() are inherited from HTMLElement.

Events

Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface:

input event

Fires when the value of an <input>, <select>, or <textarea> element has been changed.

selectionchange event Experimental

Fires when the text selection in a <textarea> element has been changed.

Examples

Autogrowing textarea example

Make a textarea autogrow while typing:

JavaScript

js

function autoGrow(oField) {
  if (oField.scrollHeight > oField.clientHeight) {
    oField.style.height = `${oField.scrollHeight}px`;
  }
}

CSS

css

textarea.noscrollbars {
  overflow: hidden;
  width: 300px;
  height: 100px;
}

HTML

html

<form>
  <fieldset>
    <legend>Your comments</legend>
    <p><textarea class="noscrollbars" onkeyup="autoGrow(this);"></textarea></p>
    <p><input type="submit" value="Send" /></p>
  </fieldset>
</form>

Insert HTML tags example

Insert some HTML tags in a textarea.

JavaScript

js

function insert(startTag, endTag) {
  const textArea = document.myForm.myTxtArea;
  const selectionStart = textArea.selectionStart;
  const selectionEnd = textArea.selectionEnd;
  const oldText = textArea.value;

  const prefix = oldText.substring(0, selectionStart);
  const inserted =
    startTag + oldText.substring(selectionStart, selectionEnd) + endTag;
  const suffix = oldText.substring(selectionEnd);
  textArea.value = `${prefix}${inserted}${suffix}`;

  const newSelectionStart = selectionStart + startTag.length;
  const newSelectionEnd = selectionEnd + startTag.length;
  textArea.setSelectionRange(newSelectionStart, newSelectionEnd);

  textArea.focus();
}

function insertURL() {
  const newURL = prompt("Enter the full URL for the link");
  if (newURL) {
    insert(`<a href="${newURL}">`, "</a>");
  } else {
    document.myForm.myTxtArea.focus();
  }
}

const strong = document.querySelector("#format-strong");
const em = document.querySelector("#format-em");
const link = document.querySelector("#format-link");
const code = document.querySelector("#format-code");

strong.addEventListener("click", (e) => insert("<strong>", "</strong>"));
em.addEventListener("click", (e) => insert("<em>", "</em>"));
link.addEventListener("click", (e) => insertURL());
code.addEventListener("click", (e) => insert("\n<code>\n", "\n</code>\n"));

CSS

CSS to decorate the internal span to behave like a link:

css

.intLink {
  cursor: pointer;
  text-decoration: underline;
  color: #0000ff;
}

HTML:

html

<form name="myForm">
  <p>
    [&nbsp;
    <span class="intLink" id="format-strong"><strong>Bold</strong></span> |
    <span class="intLink" id="format-em"><em>Italic</em></span> |
    <span class="intLink" id="format-link">URL</span> |
    <span class="intLink" id="format-code">code</span> &nbsp;]
  </p>

  <p>
    <textarea name="myTxtArea" rows="10" cols="50">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut facilisis, arcu vitae adipiscing placerat, nisl lectus accumsan nisi, vitae iaculis sem neque vel lectus. Praesent tristique commodo lorem quis fringilla. Sed ac tellus eros. Sed consectetur eleifend felis vitae luctus. Praesent sagittis, est eget bibendum tincidunt, ligula diam tincidunt augue, a fermentum odio velit eget mi. Phasellus mattis, elit id fringilla semper, orci magna cursus ligula, non venenatis lacus augue sit amet dui. Pellentesque lacinia odio id nisi pulvinar commodo tempus at odio. Ut consectetur eros porttitor nunc mollis ultrices. Aenean porttitor, purus sollicitudin viverra auctor, neque erat blandit sapien, sit amet tincidunt massa mi ac nibh. Proin nibh sem, bibendum ut placerat nec, cursus et lacus. Phasellus vel augue turpis. Nunc eu mauris eu leo blandit mollis interdum eget lorem.
    </textarea>
  </p>
</form>

Maximum length and number of lines example

Create a textarea with a maximum number of characters per line and a maximum number of lines:

First, create a function that takes the text field and a key event as input and determines if any of the limits have been reached. If the limit has not been reached, it will return the key.

js

function checkRows(oField, oKeyEvent) {
  let nKey = (
      oKeyEvent ||
      /* old IE */ window.event || /* check is not supported! */ { keyCode: 38 }
    ).keyCode,
    // put here the maximum number of characters per line:
    nCols = 30,
    // put here the maximum number of lines:
    nRows = 5,
    nSelS = oField.selectionStart,
    nSelE = oField.selectionEnd,
    sVal = oField.value,
    nLen = sVal.length,
    nBackward = nSelS >= nCols ? nSelS - nCols : 0,
    nDeltaForw =
      sVal
        .substring(nBackward, nSelS)
        .search(new RegExp(`\\n(?!.{0,${String(nCols - 2)}}\\n)`)) + 1,
    nRowStart = nBackward + nDeltaForw,
    aReturns = (
      sVal.substring(0, nSelS) + sVal.substring(nSelE, sVal.length)
    ).match(/\n/g),
    nRowEnd = nSelE + nRowStart + nCols - nSelS,
    sRow =
      sVal.substring(nRowStart, nSelS) +
      sVal.substring(nSelE, nRowEnd > nLen ? nLen : nRowEnd),
    bKeepCols =
      nKey === 13 ||
      nLen + 1 < nCols ||
      /\n/.test(sRow) ||
      ((nRowStart === 0 || nDeltaForw > 0 || nKey > 0) &&
        (sRow.length < nCols ||
          (nKey > 0 && (nLen === nRowEnd || sVal.charAt(nRowEnd) === "\n"))));

  return (
    (nKey !== 13 || (aReturns ? aReturns.length + 1 : 1) < nRows) &&
    ((nKey > 32 && nKey < 41) || bKeepCols)
  );
}

In the HTML we just need to hook our function to the onkeypress event and specify that our textarea does not accept pasting:

html

<form>
  <p>
    Textarea with fixed number of characters per line:<br />
    <textarea
      cols="50"
      rows="10"
      onkeypress="return checkRows(this, event);"
      onpaste="return false;"></textarea>
  </p>
</form>

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet
HTMLTextAreaElement 1 12 1 5 8 1 ≤37 18 4 10.1 1 1.0
autocapitalize 43 79 111 No 30 No No 43 111 30 ≤3 4.0
autocomplete 66 79 59 No 53 9.1 66 66 59 47 9.3 9.0
checkValidity 4 12 4 10 ≤12.1 5 ≤37 18 4 ≤12.1 5 1.0
cols 1 12 1 5 ≤12.1 1 4.4 18 4 ≤12.1 1 1.0
defaultValue 1 12 1 5 ≤12.1 1 4.4 18 4 ≤12.1 1 1.0
dirName 17 79 116 No ≤12.1 6 4.4 18 116 ≤12.1 6 1.0
disabled 1 12 1 5 ≤12.1 1 4.4 18 4 ≤12.1 1 1.0
form 1 12 1 5 ≤12.1 1 4.4 18 4 ≤12.1 1 1.0
labels 6 18 56 No ≤12.1 5.1 3 18 56 ≤12.1 5 1.0
maxLength 4 12 4 10 ≤12.1 5 ≤37 18 4 ≤12.1 5 1.0
minLength 40 17 51 No 27 10.1 40 40 51 27 10.3 4.0
name 1 12 1 5 ≤12.1 1 4.4 18 4 ≤12.1 1 1.0
placeholder 4 12 4 10 ≤12.1 5 ≤37 18 4 ≤12.1 5 1.0
readOnly 1 12 1 5 ≤12.1 1 4.4 18 4 ≤12.1 1 1.0
reportValidity 40 17 49 No 27 10.1 40 40 64 27 10.3 4.0
required 4 12 4 10 ≤12.1 5 ≤37 18 4 ≤12.1 5 1.0
rows 1 12 1 5 ≤12.1 1 4.4 18 4 ≤12.1 1 1.0
select 1 12 1 5 ≤12.1 1 4.4 18 4 ≤12.1 1 1.0
select_event 1 12 6 9 ≤12.1 1 4.4 18 6 ≤12.1 1 1.0
selectionDirection 15 79 8 No ≤12.1 6 4.4 18 8 ≤12.1 6 1.0
selectionEnd 1 12 1 9 ≤12.1 1.3 4.4 18 4 ≤12.1 1 1.0
selectionStart 1 12 1 9 ≤12.1 1.3 4.4 18 4 ≤12.1 1 1.0
selectionchange_event
NoA selectionchange event is fired on Document, see Document's selectionchange event. See bug 1327098 for firing the event on <textarea> elements.
NoA selectionchange event is fired on Document, see Document's selectionchange event. See bug 1327098 for firing the event on <textarea> elements.
92 No
NoA selectionchange event is fired on Document, see Document's selectionchange event. See bug 1327098 for firing the event on <textarea> elements.
No
NoA selectionchange event is fired on Document, see Document's selectionchange event. See bug 1327098 for firing the event on <textarea> elements.
NoA selectionchange event is fired on Document, see Document's selectionchange event. See bug 1327098 for firing the event on <textarea> elements.
92
NoA selectionchange event is fired on Document, see Document's selectionchange event. See bug 1327098 for firing the event on <textarea> elements.
No
NoA selectionchange event is fired on Document, see Document's selectionchange event. See bug 1327098 for firing the event on <textarea> elements.
setCustomValidity 4 12 4 10 ≤12.1 5 ≤37 18 4 ≤12.1 5 1.0
setRangeText 24 79 27 No 15 7 4.4 25 27 14 7 1.5
setSelectionRange 1 12 1 9 ≤12.1 1.3 4.4 18 4 ≤12.1 1 1.0
textLength 4 17 1 No ≤12.1 5 ≤37 18 4 ≤12.1 4 1.0
type 1 12 1 5 ≤12.1 1 4.4 18 4 ≤12.1 1 1.0
validationMessage 5 12 4 10 ≤12.1 5 ≤37 18 4 ≤12.1 5 1.0
validity 4 12 4 10 ≤12.1 5 ≤37 18 4 ≤12.1 5 1.0
value 1 12 1 5 ≤12.1 1 4.4 18 4 ≤12.1 1 1.0
willValidate 2 12 4 10 ≤12.1 4 ≤37 18 4 ≤12.1 3.2 1.0
wrap 16 12 4 5 ≤12.1 6 4.4 18 4 ≤12.1 6 1.0

© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLTextAreaElement