Revision 404021 of HTMLTextAreaElement

  • Revision slug: Web/API/HTMLTextAreaElement
  • Revision title: HTMLTextAreaElement
  • Revision id: 404021
  • Created:
  • Creator: Sheppy
  • Is current revision? No
  • Comment DOM/HTMLTextAreaElement Web/API/HTMLTextAreaElement

Revision Content

HTML TextArea element Interface

DOM TextArea objects expose the HTMLTextAreaElement (or {{ HTMLVersionInline(4) }} HTMLTextAreaElement) interface, which provides special properties and methods (beyond the regular element object interface they also have available to them by inheritance) for manipulating the layout and presentation of {{ HTMLElement("textarea") }} elements.

Properties

Name Type Description Availability
accessKey {{ HTMLVersionInline(4) }} DOMString Reflects the {{ htmlattrxref("accesskey", "textarea") }} HTML attribute. {{ obsolete_inline() }} in {{ HTMLVersionInline(5) }} All
autofocus {{ HTMLVersionInline(5) }} Boolean Reflects the {{ htmlattrxref("autofocus", "textarea") }} HTML attribute, indicating that the control should have input focus when the page loads All
cols unsigned long Reflects the {{ htmlattrxref("cols", "textarea") }} HTML attribute, indicating the visible width of the text area. All
defaultValue DOMString The control's default value, which behaves like the textContent property. All
disabled Boolean Reflects the {{ htmlattrxref("disabled", "textarea") }} HTML attribute, indicating that the control is not available for interaction. All
form Readonly HTMLFormElement

The containing form element, if this element is in a form. If this element is not contained in a form element:

  • {{ HTMLVersionInline(5) }} this can be the {{ htmlattrxref("id", "form") }} attribute of any {{ HTMLElement("form") }} element in the same document.
  • {{ HTMLVersionInline(4) }} this must be null.
All
labels {{ HTMLVersionInline(5) }} {{ unimplemented_inline(556743) }} readonly NodeList A list of {{ HTMLElement("label") }} elements that are labels for this element. All
maxLength {{ HTMLVersionInline(5) }} long Reflects the {{ htmlattrxref("maxlength", "textarea") }} HTML attribute, indicating the maximum number of characters the user can enter. This constraint is evaluated only when the value changes. All
name DOMString Reflects {{ htmlattrxref("name", "textarea") }} HTML attribute, containing the name of the control. All
placeholder {{ HTMLVersionInline(5) }} DOMString Reflects the {{ htmlattrxref("placeholder", "textarea") }} HTML attribute, containing a hint to the user about what to enter in the control. All
readOnly Boolean Reflects the {{ htmlattrxref("readonly", "textarea") }} HTML attribute, indicating that the user cannot modify the value of the control. All
required {{ HTMLVersionInline(5) }} Boolean Reflects the {{ htmlattrxref("required", "textarea") }} HTML attribute, indicating that the user must specify a value before submitting the form. All
rows unsigned long Reflects the {{ htmlattrxref("rows", "textarea") }} HTML attribute, indicating the number of visible text lines for the control. All
selectionDirection {{ HTMLVersionInline(5) }} DOMString The direction in which selection occurred. This is "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." All
selectionEnd {{ HTMLVersionInline(5) }} unsigned long The index of the end of selected text. {{ HTMLVersionInline(5) }} 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. All
selectionStart {{ HTMLVersionInline(5) }} unsigned long The index of the beginning of selected text. {{ HTMLVersionInline(5) }} 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. All
tabIndex {{ HTMLVersionInline(4) }} long The position of the element in the tabbing navigation order for the current document. {{ obsolete_inline() }} in {{ HTMLVersionInline(5) }} All
textLength {{ HTMLVersionInline(5) }} readonly long The codepoint length of the control's value. All
type readonly DOMString The string textarea. All
validationMessage {{ HTMLVersionInline(5) }} readonly DOMString 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. All
validity {{ HTMLVersionInline(5) }} readonly ValidityStates The validity states that this element is in. All
value DOMString The raw value contained in the control. All
willValidate {{ HTMLVersionInline(5) }} Boolean Indicates whether the element is a candidate for constraint validation. It is false if any conditions bar it from constraint validation. All
wrap {{ HTMLVersionInline(5) }} DOMString Reflects the {{ htmlattrxref("wrap", "textarea") }} HTML attribute, indicating how the control wraps text. All {{ gecko_minversion_inline("2.0") }}

Methods

Name & Arguments Return Description Availability
blur() {{ HTMLVersionInline(4) }} void Removes input focus from this control. {{ obsolete_inline() }} in {{ HTMLVersionInline(5) }} All
checkValidity() {{ HTMLVersionInline(5) }} Boolean Returns false if the button is a candidate for constraint validation, and it does not satisfy its constraints. In this case, it also fires an invalid event at the control. It returns true if the control is not a candidate for constraint validation, or if it satisfies its constraints. All
focus() {{ HTMLVersionInline(4) }} void Gives input focus to this control. All
select() void Selects the contents of the control. All
setCustomValidity(in DOMString error) {{ HTMLVersionInline(5) }} void 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. All
setSelectionRange(selectionStart, selectionEnd, [optional] selectionDirection) {{ HTMLVersionInline(5) }} void Selects a range of text, and sets selectionStart and selectionEnd. If either argument is greater than the length of the value, it is treated as pointing to the end of the value. If end is less than start, then both are treated as the value of end. All

Examples

Autogrowing textarea example

The following example shows how to make a textarea really autogrow while typing.

Here is the JavaScript function:

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

CSS:

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

HTML:

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

{{ EmbedLiveSample('Autogrowing_textarea_example', 600, 300) }}

Insert HTML tags example

The following example shows how to insert some HTML tags or smiles or any custom text in a textarea. First we create a JavaScript function:

function insertMetachars(sStartTag, sEndTag) {
	var bDouble = arguments.length > 1, oMsgInput = document.myForm.myTxtArea, nSelStart = oMsgInput.selectionStart, nSelEnd = oMsgInput.selectionEnd, sOldText = oMsgInput.value;
	oMsgInput.value = sOldText.substring(0, nSelStart) + (bDouble ? sStartTag + sOldText.substring(nSelStart, nSelEnd) + sEndTag : sStartTag) + sOldText.substring(nSelEnd);
	oMsgInput.setSelectionRange(bDouble || nSelStart === nSelEnd ? nSelStart + sStartTag.length : nSelStart, (bDouble ? nSelEnd : nSelStart) + sStartTag.length);
	oMsgInput.focus();
}

Add a little bit of CSS to decorate the internal span to behave like a link:

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

And here is the HTML:

<form name="myForm">
<p>[&nbsp;<span class="intLink" onclick="insertMetachars('&lt;strong&gt;','&lt;\/strong&gt;');"><strong>Bold</strong></span> | <span class="intLink" onclick="insertMetachars('&lt;em&gt;','&lt;\/em&gt;');"><em>Italic</em></span> | <span class="intLink" onclick="var newURL=prompt('Enter the full URL for the link');if(newURL){insertMetachars('&lt;a href=\u0022'+newURL+'\u0022&gt;','&lt;\/a&gt;');}else{document.myForm.myTxtArea.focus();}">URL</span> | <span class="intLink" onclick="insertMetachars('\n&lt;code&gt;\n','\n&lt;\/code&gt;\n');">code</span> | <span class="intLink" onclick="insertMetachars(' :-)');">smile</span> | etc. etc.&nbsp;]</p>
<p><textarea rows="10" cols="50" name="myTxtArea">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>

{{ EmbedLiveSample('Insert_HTML_tags_example', 600, 300) }}

Maximum length and number of lines example

The following example shows how to create a textarea with a maximum number of characters per line and a maximum number of lines. First we 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.

function checkRows(oField, oKeyEvent) {
	var	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:

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

{{ EmbedLiveSample('Maximum_length_and_number_of_lines_example', 600, 300) }}

Revision Source

<h3 id="HTML_TextArea_Element_Interface" name="HTML_TextArea_Element_Interface">HTML TextArea element Interface</h3>
<p>DOM <code>TextArea</code> objects expose the <a class="external" href="http://dev.w3.org/html5/spec/the-button-element.html#the-textarea-element" title="http://dev.w3.org/html5/spec/the-button-element.html#the-textarea-element">HTMLTextAreaElement</a> (or {{ HTMLVersionInline(4) }} <code><a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-24874179" title="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-24874179">HTMLTextAreaElement</a></code>) interface, which provides special properties and methods (beyond the regular <a href="/en/DOM/element" title="en/DOM/element">element</a> object interface they also have available to them by inheritance) for manipulating the layout and presentation of {{ HTMLElement("textarea") }} elements.</p>
<h3 id="Properties" name="Properties">Properties</h3>
<table class="fullwidth-table">
  <tbody>
    <tr>
      <th>Name</th>
      <th>Type</th>
      <th>Description</th>
      <th>Availability</th>
    </tr>
    <tr>
      <td><code>accessKey</code> {{ HTMLVersionInline(4) }}</td>
      <td><code><a href="/En/DOM/DOMString" title="En/DOM/DOMString"><span style="text-decoration: underline;">DOMString</span></a></code></td>
      <td>Reflects the {{ htmlattrxref("accesskey", "textarea") }} HTML attribute. {{ obsolete_inline() }} in {{ HTMLVersionInline(5) }}</td>
      <td nowrap="nowrap"><small><a href="/en/DOM" title="en/DOM">All</a></small></td>
    </tr>
    <tr>
      <td><code>autofocus</code> {{ HTMLVersionInline(5) }}</td>
      <td><code><a href="/en/JavaScript/Reference/Global_Objects/Boolean" title="en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">Boolean</a></code></td>
      <td>Reflects the {{ htmlattrxref("autofocus", "textarea") }} HTML&nbsp;attribute, indicating that the control should have input focus when the page loads</td>
      <td nowrap="nowrap"><small><a href="/en/DOM" title="en/DOM">All</a></small></td>
    </tr>
    <tr>
      <td><code>cols</code></td>
      <td><code>unsigned long</code></td>
      <td>Reflects the {{ htmlattrxref("cols", "textarea") }} HTML attribute, indicating the visible width of the text area.</td>
      <td nowrap="nowrap"><small><a href="/en/DOM" title="en/DOM">All</a></small></td>
    </tr>
    <tr>
      <td><code>defaultValue</code></td>
      <td><code><a href="/En/DOM/DOMString" title="En/DOM/DOMString"><span style="text-decoration: underline;">DOMString</span></a></code></td>
      <td>The control's default value, which behaves like the <strong><a href="/En/DOM/Node.textContent" title="en/DOM/element.textContent">textContent</a></strong> property.</td>
      <td nowrap="nowrap"><small><a href="/en/DOM" title="en/DOM">All</a></small></td>
    </tr>
    <tr>
      <td><code>disabled</code></td>
      <td><code><a href="/en/JavaScript/Reference/Global_Objects/Boolean" title="en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">Boolean</a></code></td>
      <td>Reflects the {{ htmlattrxref("disabled", "textarea") }} HTML attribute, indicating that the control is not available for interaction.</td>
      <td nowrap="nowrap"><small><a href="/en/DOM" title="en/DOM">All</a></small></td>
    </tr>
    <tr>
      <td><code>form</code></td>
      <td><code>Readonly <a href="/en/DOM/HTMLFormElement" title="en/DOM/Form">HTMLFormElement</a></code></td>
      <td>
        <p>The containing form element, if this element is in a form. If this element is not contained in a form element:</p>
        <ul>
          <li>{{ HTMLVersionInline(5) }} this can be the {{ htmlattrxref("id", "form") }} attribute of any {{ HTMLElement("form") }} element in the same document.</li>
          <li>{{ HTMLVersionInline(4) }} this must be <code>null</code>.</li>
        </ul>
      </td>
      <td nowrap="nowrap"><small><a href="/en/DOM" title="en/DOM">All</a></small></td>
    </tr>
    <tr>
      <td><code>labels</code> {{ HTMLVersionInline(5) }} {{ unimplemented_inline(556743) }}</td>
      <td><code>readonly <a href="/En/DOM/NodeList" title="En/DOM/NodeList">NodeList</a></code></td>
      <td>A list of {{ HTMLElement("label") }} elements that are labels for this element.</td>
      <td nowrap="nowrap"><small><a href="/en/DOM" title="en/DOM">All</a></small></td>
    </tr>
    <tr>
      <td><code>maxLength </code>{{ HTMLVersionInline(5) }}</td>
      <td><code>long</code></td>
      <td>Reflects the {{ htmlattrxref("maxlength", "textarea") }} HTML&nbsp;attribute, indicating the maximum number of characters the user can enter. This constraint is evaluated only when the value changes.</td>
      <td nowrap="nowrap"><small><a href="/en/DOM" title="en/DOM">All</a></small></td>
    </tr>
    <tr>
      <td><code>name</code></td>
      <td><code><a href="/En/DOM/DOMString" title="En/DOM/DOMString"><span style="text-decoration: underline;">DOMString</span></a></code></td>
      <td>Reflects {{ htmlattrxref("name", "textarea") }} HTML attribute, containing the name of the control.</td>
      <td nowrap="nowrap"><small><a href="/en/DOM" title="en/DOM">All</a></small></td>
    </tr>
    <tr>
      <td><code>placeholder</code> {{ HTMLVersionInline(5) }}</td>
      <td><code><a href="/En/DOM/DOMString" title="En/DOM/DOMString"><span style="text-decoration: underline;">DOMString</span></a></code></td>
      <td>Reflects the {{ htmlattrxref("placeholder", "textarea") }} HTML attribute, containing a hint to the user about what to enter in the control.</td>
      <td nowrap="nowrap"><small><a href="/en/DOM" title="en/DOM">All</a></small></td>
    </tr>
    <tr>
      <td><code>readOnly</code></td>
      <td><code><a href="/en/JavaScript/Reference/Global_Objects/Boolean" title="en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">Boolean</a></code></td>
      <td>Reflects the {{ htmlattrxref("readonly", "textarea") }} HTML attribute, indicating that the user cannot modify the value of the control.</td>
      <td nowrap="nowrap"><small><a href="/en/DOM" title="en/DOM">All</a></small></td>
    </tr>
    <tr>
      <td><code>required</code> {{ HTMLVersionInline(5) }}</td>
      <td><code><a href="/en/JavaScript/Reference/Global_Objects/Boolean" title="en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">Boolean</a></code></td>
      <td>Reflects the {{ htmlattrxref("required", "textarea") }} HTML attribute, indicating that the user must specify a value before submitting the form.</td>
      <td nowrap="nowrap"><small><a href="/en/DOM" title="en/DOM">All</a></small></td>
    </tr>
    <tr>
      <td><code>rows</code></td>
      <td><code>unsigned long</code></td>
      <td>Reflects the {{ htmlattrxref("rows", "textarea") }} HTML attribute, indicating the number of visible text lines for the control.</td>
      <td nowrap="nowrap"><small><a href="/en/DOM" title="en/DOM">All</a></small></td>
    </tr>
    <tr>
      <td><code>selectionDirection</code> {{ HTMLVersionInline(5) }}</td>
      <td><code><a href="/En/DOM/DOMString" title="En/DOM/DOMString">DOMString</a></code></td>
      <td>The direction in which selection occurred. This is "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"&nbsp;if the direction is unknown."</td>
      <td nowrap="nowrap"><small><a href="/en/DOM" title="en/DOM">All</a></small></td>
    </tr>
    <tr>
      <td><code>selectionEnd </code>{{ HTMLVersionInline(5) }}</td>
      <td><code>unsigned long</code></td>
      <td>The index of the end of selected text. {{ HTMLVersionInline(5) }} If no text is selected, contains the index of the character that follows the input cursor. On being set, the control behaves as if <strong>setSelectionRange</strong>() had been called with this as the second argument, and <strong>selectionStart</strong> as the first argument.</td>
      <td nowrap="nowrap"><small><a href="/en/DOM" title="en/DOM">All</a></small></td>
    </tr>
    <tr>
      <td><code>selectionStart </code>{{ HTMLVersionInline(5) }}</td>
      <td><code>unsigned long</code></td>
      <td>The index of the beginning of selected text. {{ HTMLVersionInline(5) }} If no text is selected, contains the index of the character that follows the input cursor. On being set, the control behaves as if <strong>setSelectionRange</strong>() had been called with this as the first argument, and <strong>selectionEnd</strong> as the second argument.</td>
      <td nowrap="nowrap"><small><a href="/en/DOM" title="en/DOM">All</a></small></td>
    </tr>
    <tr>
      <td><code>tabIndex </code>{{ HTMLVersionInline(4) }}</td>
      <td><code>long</code></td>
      <td>The position of the element in the tabbing navigation order for the current document. {{ obsolete_inline() }} in {{ HTMLVersionInline(5) }}</td>
      <td nowrap="nowrap"><small><a href="/en/DOM" title="en/DOM">All</a></small></td>
    </tr>
    <tr>
      <td><code>textLength </code>{{ HTMLVersionInline(5) }}</td>
      <td><code>readonly long</code></td>
      <td>The codepoint length of the control's value.</td>
      <td nowrap="nowrap"><small><a href="/en/DOM" title="en/DOM">All</a></small></td>
    </tr>
    <tr>
      <td><code>type</code></td>
      <td><code>readonly <a href="/En/DOM/DOMString" title="En/DOM/DOMString">DOMString</a></code></td>
      <td>The string <code>textarea</code>.</td>
      <td nowrap="nowrap"><small><a href="/en/DOM" title="en/DOM">All</a></small></td>
    </tr>
    <tr>
      <td><code>validationMessage</code> {{ HTMLVersionInline(5) }}</td>
      <td><code>readonly <a href="/En/DOM/DOMString" title="En/DOM/DOMString">DOMString</a></code></td>
      <td>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 (<strong>willValidate</strong> is false), or it satisfies its constraints.</td>
      <td><small><a href="/en/DOM" title="en/DOM">All</a></small></td>
    </tr>
    <tr>
      <td><code>validity</code> {{ HTMLVersionInline(5) }}</td>
      <td><code>readonly <a href="/en/DOM/ValidityStates_Interface" title="en/DOM/ValidityStates Interface">ValidityStates</a></code></td>
      <td>The validity states that this element is in.</td>
      <td><small><a href="/en/DOM" title="en/DOM">All</a></small></td>
    </tr>
    <tr>
      <td><code>value</code></td>
      <td><code><a href="/En/DOM/DOMString" title="En/DOM/DOMString"><span style="text-decoration: underline;">DOMString</span></a></code></td>
      <td>The raw value contained in the control.</td>
      <td nowrap="nowrap"><small><a href="/en/DOM" title="en/DOM">All</a></small></td>
    </tr>
    <tr>
      <td><code>willValidate</code> {{ HTMLVersionInline(5) }}</td>
      <td><code><a href="/en/JavaScript/Reference/Global_Objects/Boolean" title="en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">Boolean</a></code></td>
      <td>Indicates whether the element is a candidate for constraint validation. It is false if any conditions bar it from constraint validation.</td>
      <td nowrap="nowrap"><small><a href="/en/DOM" title="en/DOM">All</a></small></td>
    </tr>
    <tr>
      <td><code>wrap</code> {{ HTMLVersionInline(5) }}</td>
      <td><code><a href="/En/DOM/DOMString" title="En/DOM/DOMString"><span style="text-decoration: underline;">DOMString</span></a></code></td>
      <td>Reflects the {{ htmlattrxref("wrap", "textarea") }} HTML attribute, indicating how the control wraps text.</td>
      <td nowrap="nowrap"><small><a href="/en/DOM" title="en/DOM">All</a></small> {{ gecko_minversion_inline("2.0") }}</td>
    </tr>
  </tbody>
</table>
<h3 id="Methods" name="Methods">Methods</h3>
<table class="fullwidth-table">
  <tbody>
    <tr>
      <th>Name &amp; Arguments</th>
      <th>Return</th>
      <th>Description</th>
      <th>Availability</th>
    </tr>
    <tr>
      <td><code>blur() </code>{{ HTMLVersionInline(4) }}</td>
      <td><code>void</code></td>
      <td>Removes input focus from this control. {{ obsolete_inline() }} in {{ HTMLVersionInline(5) }}</td>
      <td nowrap="nowrap"><small><a href="/en/DOM/event" title="en/DOM/event">All</a></small></td>
    </tr>
    <tr>
      <td><code>checkValidity() </code>{{ HTMLVersionInline(5) }}</td>
      <td><code><a href="/en/JavaScript/Reference/Global_Objects/Boolean" title="en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">Boolean</a></code></td>
      <td>Returns false if the button is a candidate for constraint validation, and it does not satisfy its constraints. In this case, it also fires an <code>invalid</code> event at the control. It returns true if the control is not a candidate for constraint validation, or if it satisfies its constraints.</td>
      <td nowrap="nowrap"><small><a href="/en/DOM/event" title="en/DOM/event">All</a></small></td>
    </tr>
    <tr>
      <td><code>focus() </code>{{ HTMLVersionInline(4) }}</td>
      <td><code>void </code></td>
      <td>Gives input focus to this control.</td>
      <td nowrap="nowrap"><small><a href="/en/DOM/event" title="en/DOM/event">All</a></small></td>
    </tr>
    <tr>
      <td><code>select() </code></td>
      <td><code>void</code></td>
      <td>Selects the contents of the control.</td>
      <td nowrap="nowrap"><small><a href="/en/DOM/event" title="en/DOM/event">All</a></small></td>
    </tr>
    <tr>
      <td><code>setCustomValidity(in DOMString error) </code>{{ HTMLVersionInline(5) }}</td>
      <td><code>void</code></td>
      <td>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.</td>
      <td nowrap="nowrap"><small><a href="/en/DOM/event" title="en/DOM/event">All</a></small></td>
    </tr>
    <tr>
      <td><code><a href="/en/DOM/Input.setSelectionRange" title="en/DOM/Input.setSelectionRange">setSelectionRange</a>(selectionStart, selectionEnd, [optional] selectionDirection)</code><code> </code>{{ HTMLVersionInline(5) }}</td>
      <td><code>void</code></td>
      <td>Selects a range of text, and sets <code>selectionStart</code> and <code>selectionEnd</code>. If either argument is greater than the length of the value, it is treated as pointing to the end of the value. If <code>end</code> is less than <code>start</code>, then both are treated as the value of <code>end</code>.</td>
      <td nowrap="nowrap"><small><a href="/en/DOM" title="en/DOM">All</a></small></td>
    </tr>
  </tbody>
</table>
<h3 id="Examples">Examples</h3>
<h4 id="Autogrowing_textarea_example">Autogrowing textarea example</h4>
<p>The following example shows how to make a textarea really autogrow while typing.</p>
<p>Here is the JavaScript function:</p>
<pre class="brush: js">
function autoGrow (oField) {
&nbsp; if (oField.scrollHeight &gt; oField.clientHeight) {
&nbsp;&nbsp;&nbsp; oField.style.height = oField.scrollHeight + "px";
&nbsp; }
}</pre>
<p>CSS:</p>
<pre class="brush: css">
textarea.noscrollbars {
&nbsp; overflow: hidden;
&nbsp; width: 300px;
&nbsp; height: 100px;
}</pre>
<p>HTML:</p>
<pre class="brush: html">
&lt;form name="myForm"&gt;
&nbsp; &lt;fieldset&gt; &nbsp;
&nbsp;&nbsp;&nbsp; &lt;legend&gt;Your comments&lt;/legend&gt; &nbsp;
&nbsp;&nbsp;&nbsp; &lt;p&gt;&lt;textarea class="noscrollbars" onkeyup="autoGrow(this);"&gt;&lt;/textarea&gt;&lt;/p&gt;
&nbsp;&nbsp;&nbsp; &lt;p&gt;&lt;input type="submit" value="Send" /&gt;&lt;/p&gt;
&nbsp; &lt;/fieldset&gt;
&lt;/form&gt;
</pre>
<p>{{ EmbedLiveSample('Autogrowing_textarea_example', 600, 300) }}</p>
<h4 id="Insert_HTML_tags_example">Insert HTML tags example</h4>
<p>The following example shows how to insert some HTML tags or <em>smiles</em> or any custom text in a textarea. First we create a JavaScript function:</p>
<pre class="brush: js">
function insertMetachars(sStartTag, sEndTag) {
	var bDouble = arguments.length &gt; 1, oMsgInput = document.myForm.myTxtArea, nSelStart = oMsgInput.selectionStart, nSelEnd = oMsgInput.selectionEnd, sOldText = oMsgInput.value;
	oMsgInput.value = sOldText.substring(0, nSelStart) + (bDouble ? sStartTag + sOldText.substring(nSelStart, nSelEnd) + sEndTag : sStartTag) + sOldText.substring(nSelEnd);
	oMsgInput.setSelectionRange(bDouble || nSelStart === nSelEnd ? nSelStart + sStartTag.length : nSelStart, (bDouble ? nSelEnd : nSelStart) + sStartTag.length);
	oMsgInput.focus();
}</pre>
<p>Add a little bit of CSS to decorate the internal span to behave like a link:</p>
<pre class="brush: css">
.intLink {
	cursor: pointer;
	text-decoration: underline;
	color: #0000ff;
}</pre>
<p>And here is the HTML:</p>
<pre class="brush: html">
&lt;form name="myForm"&gt;
&lt;p&gt;[&amp;nbsp;&lt;span class="intLink" onclick="insertMetachars('&amp;lt;strong&amp;gt;','&amp;lt;\/strong&amp;gt;');"&gt;&lt;strong&gt;Bold&lt;/strong&gt;&lt;/span&gt; | &lt;span class="intLink" onclick="insertMetachars('&amp;lt;em&amp;gt;','&amp;lt;\/em&amp;gt;');"&gt;&lt;em&gt;Italic&lt;/em&gt;&lt;/span&gt; | &lt;span class="intLink" onclick="var newURL=prompt('Enter the full URL for the link');if(newURL){insertMetachars('&amp;lt;a href=\u0022'+newURL+'\u0022&amp;gt;','&amp;lt;\/a&amp;gt;');}else{document.myForm.myTxtArea.focus();}"&gt;URL&lt;/span&gt; | &lt;span class="intLink" onclick="insertMetachars('\n&amp;lt;code&amp;gt;\n','\n&amp;lt;\/code&amp;gt;\n');"&gt;code&lt;/span&gt; | &lt;span class="intLink" onclick="insertMetachars(' :-)');"&gt;smile&lt;/span&gt; | etc. etc.&amp;nbsp;]&lt;/p&gt;
&lt;p&gt;&lt;textarea rows="10" cols="50" name="myTxtArea"&gt;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. &lt;/textarea&gt;&lt;/p&gt;
&lt;/form&gt;
</pre>
<p>{{ EmbedLiveSample('Insert_HTML_tags_example', 600, 300) }}</p>
<h4 id="Maximum_length_and_number_of_lines_example">Maximum length and number of lines example</h4>
<p>The following example shows how to create a textarea with a maximum number of characters per line and a maximum number of lines. First we 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.</p>
<pre class="brush: js">
function checkRows(oField, oKeyEvent) {
	var	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 &gt;= 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 &gt; nLen ? nLen : nRowEnd),
		bKeepCols = nKey === 13 || nLen + 1 &lt; nCols || /\n/.test(sRow) || ((nRowStart === 0 || nDeltaForw &gt; 0 || nKey &gt; 0) &amp;&amp; (sRow.length &lt; nCols || (nKey &gt; 0 &amp;&amp; (nLen === nRowEnd || sVal.charAt(nRowEnd) === "\n"))));

	return (nKey !== 13 || (aReturns ? aReturns.length + 1 : 1) &lt; nRows) &amp;&amp; ((nKey &gt; 32 &amp;&amp; nKey &lt; 41) || bKeepCols);
}</pre>
<p>In the HTML we just need to hook our function to the `onkeypress` event and specify that our textarea does not accept pasting:</p>
<pre class="brush: html">
&lt;form&gt;
&lt;p&gt;Textarea with fixed number of characters per line:&lt;br /&gt;
&lt;textarea cols="50" rows="10" name="myInput" onkeypress="return checkRows(this, event);" onpaste="return false;" /&gt;&lt;/textarea&gt;&lt;/p&gt;
&lt;/form&gt;
</pre>
<p>{{ EmbedLiveSample('Maximum_length_and_number_of_lines_example', 600, 300) }}</p>
Revert to this revision