Получение данных из поля textarea примеры

Алан-э-Дейл       11.03.2024 г.

Advanced Topics #

Why Controlled Components?

Using form components such as in React presents a challenge that is absent when writing traditional form HTML. For example, in HTML:

This renders an input initialized with the value, . When the user updates the input, the node’s property will change. However, will still return the value used at initialization time, .

Unlike HTML, React components must represent the state of the view at any point in time and not only at initialization time. For example, in React:

Since this method describes the view at any point in time, the value of the text input should always be .

Why Textarea Value?

In HTML, the value of is usually set using its children:

For HTML, this easily allows developers to supply multiline values. However, since React is JavaScript, we do not have string limitations and can use if we want newlines. In a world where we have and , it is ambiguous what role children play. For this reason, you should not use children when setting values:

If you do decide to use children, they will behave like .

Why Select Value?

The selected in an HTML is normally specified through that option’s attribute. In React, in order to make components easier to manipulate, the following format is adopted instead:

To make an uncontrolled component, is used instead.

Imperative operations

If you need to imperatively perform an operation, you have to obtain a .
For instance, if you want to imperatively submit a form, one approach would be to attach a to the element and manually call .

← Prev

Next →

Methods

This section describes the methods that control the TextArea UI component.

Name Description

Prevents the UI component from refreshing until the method is called.

Removes focus from the input element.

Specifies the device-dependent default configuration properties for this component.

Disposes of all the resources allocated to the TextArea instance.

Gets the root UI component element.

Refreshes the UI component after a call of the method.

Sets focus to the input element representing the UI component.

Gets the instance of a UI component found using its DOM node.

Gets the UI component’s instance. Use it to access other methods of the UI component.

Detaches all event handlers from a single event.

Detaches a particular event handler from a single event.

Subscribes to an event.

Subscribes to events.

Gets all UI component properties.

Gets the value of a single property.

Updates the value of a single property.

Updates the values of several properties.

Registers a handler to be executed when a user presses a specific key.

Repaints the UI component without reloading data. Call it to update the UI component’s markup.

Resets the property to the default value.

Resets a property to its default value.

HTML Reference

HTML by AlphabetHTML by CategoryHTML Browser SupportHTML AttributesHTML Global AttributesHTML EventsHTML ColorsHTML CanvasHTML Audio/VideoHTML Character SetsHTML DoctypesHTML URL EncodeHTML Language CodesHTML Country CodesHTTP MessagesHTTP MethodsPX to EM ConverterKeyboard Shortcuts

HTML Tags

<!—>
<!DOCTYPE>
<a>
<abbr>
<acronym>
<address>
<applet>
<area>
<article>
<aside>
<audio>
<b>
<base>
<basefont>
<bdi>
<bdo>
<big>
<blockquote>
<body>
<br>
<button>
<canvas>
<caption>
<center>
<cite>
<code>
<col>
<colgroup>
<data>
<datalist>
<dd>
<del>
<details>
<dfn>
<dialog>
<dir>
<div>
<dl>
<dt>
<em>
<embed>
<fieldset>
<figcaption>
<figure>
<font>
<footer>
<form>
<frame>
<frameset>
<h1> — <h6>
<head>
<header>
<hr>
<html>
<i>
<iframe>
<img>
<input>
<ins>
<kbd>
<label>
<legend>
<li>
<link>
<main>
<map>
<mark>
<meta>
<meter>
<nav>
<noframes>
<noscript>
<object>
<ol>
<optgroup>
<option>
<output>
<p>
<param>
<picture>
<pre>
<progress>
<q>
<rp>
<rt>
<ruby>
<s>
<samp>
<script>
<section>
<select>
<small>
<source>
<span>
<strike>
<strong>
<style>
<sub>
<summary>
<sup>
<svg>
<table>
<tbody>
<td>
<template>
<textarea>
<tfoot>
<th>
<thead>
<time>
<title>
<tr>
<track>
<tt>
<u>
<ul>
<var>
<video>
<wbr>

Disable the placeholder when you click (focus) on an input field or textarea

The default behavior of placeholder texts when you click/focus on an input/textarea is the placeholder texts remain visible until you start typing. To make sure the placeholder text disappears as soon as you click/focus on an input or textarea is by making the placeholder text color transparent. The following CSS rules will entirely hide the placeholder text on focus/click:

::-webkit-input-placeholder { /* WebKit, Blink, Edge */
color: transparent;
}
:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
color: transparent;
}
::-moz-placeholder { /* Mozilla Firefox 19+ */
color: transparent;
}
:-ms-input-placeholder { /* Internet Explorer 10-11 */
color: transparent;
}
:placeholder-shown { /* Standard Pseudo-class */
color: transparent;
}

attributes

We mentioned above that as <textarea> is an element who got to be changed and improved a lot with the usage of HTML5. This happened because a number of new attributes were added to it.

2.1 HTML Attributes

Two of the most basic attributes of the element are and , both of the integer format, which are used to specify the visible width and length respectively of the input section in regards to an average character size. If specified, they must both be a positive number, else the default value is .

The attribute is a boolean value that shows whether or not the user is to interact with the control. By default this attribute is set to 0, or otherwise inherited by the parent element.

The attribute is used to give a name to the control which can be used later to manipulate it’s information.

Another attribute which has been there since the beginning is , which is a boolean value that shows whether or not the control should be read-only. The difference between this one and is that it doesn’t prevent the user from selecting text or clicking in the control, while the first one does. However, does allow to submit the value of the textarea with the form.

sets or returns the default value of the control in case it is not completed by the user while returns a reference to the form that contains the text area. We use to set or return the contents of the element, and to get the type of the form element the text area is.

2.2 HTML5 Attributes

Some of the most important attributes that were added with HTML5 are: autocomplete, autofocus, form, maxlength, minlength, placeholder, required, selectionDirection, spellcheck, wrap etc. Let’s see what they do each at a time.

  • – shows whether or not the browser should automatically complete the value of the control or not. When set to the browser does not autocomplete the value, so it’s either explicitly entered by the user or autocompleted by the methods of the document. Otherwise, the browser automatically completes the value based on other values previously entered by the user in the form.
  • – is a boolean value that allows the control to have input focus when the page loads. Only one of the input fields can have this attribute set to in a form.
  • – returns the ID value of the containing form element. In the cases where the <textarea> element is not a descendant of a form element, it will either return the ID value of the containing element, or .
  • – specifies the number of characters to be inserted in the control. Usually, it is specified only when you want it to be a different value from that of the default, otherwise it’s left untouched. There is also a similar attribute named . Can you guess what it does?
  • – is a string which normally offers the user an idea about what to enter in the control. However, it can be whatever you want it to be, and being funny and creative always pays off *hint-hint*.
  • – is used to indicate a value which is customary to be filled before submitting the form, which would make it unable to be submitted if it’s left uncompleted.
  • – is an attribute which specifies the direction in which the selection is required to happen. It can either be in case the selection happens from the start to finish, or in case the selection happens starting from the end and going until the start, or in case both of these options are allowed and we have no information on the direction.
  • – is a boolean value which when set to shows that the element is to have it’s grammar and spelling checked, and to be left as it is in case it’s set to . It’s value can be inherited from the parent element of which the <textarea> element is descended.
  • – is an attribute that indicates how the control wraps text. It can have two values: and . The first one inserts a line break so that each line has no more character than the width of the control, which is also why setting the attribute to this value, you will have to also specify the value. The second one, , is also the default value for in case it’s left unspecified, and is used to show the browser that it’s to respect any line break pair (CR+LF) but not insert any on it’s own accord.

With that, we have explained the most used and most important attributes regarding the <textarea> element.

Использование тега

Для ввода многострочного текста, например, при оставлении комментариев или отправки сообщений, в HTML 5
предусмотрен отдельный элемент «textarea», формирующийся парным
тегом <textarea>
(от англ. textarea – текстовая область). В отличие от текстового поля
«input» в элементе «textarea» допустимо делать переносы
строк, которые сохраняются при отправке данных на сервер. Отметим, что внутри контейнера «textarea» разрешается
писать любой текст, включая конструкции тегов. Этот текст будет отображаться браузером внутри текстового поля и при желании может быть удален
пользователем во избежание отправки на сервер вместе с остальными данными.

Обнаружение изменений при вводе текста

Атрибут у поля формы позволяет использовать CSS-правило . Тогда только с помощью CSS и без Javascript, можно легко определить, есть ли в значение. Когда значение атрибута текстового должно быть видимым, в текстовом поле (из примера кода выше) будет показываться прозрачный пробел. Если браузер показывает содержимое из , точно известно, что у нет значения, т.е. поле не заполнено.

После ввода в текстовое поле текста браузер автоматически скрывает его . Это не будет заметно, поскольку в нём используется прозрачный пробел. Зато технически теперь у текстового поля есть значение, а браузер переключил отображаемое состояние подсказки (). Это состояние позволяет CSS управлять другими элементами в зависимости от того, есть ли в текстовом поле какое-нибудь значение или нет.

Как работает CSS-правило

Для того, чтобы добавить эффектный прыжок подсказки из поля наружу, нужны следующие условия:

  1. Фокус помещён в текстовом поле
  2. У есть какое-то значение. Это рассмотренный выше случай, когда скрывается .

Вот как написать эти условия в CSS:

Фрагмент CSS устанавливает стиль подписи-метки в зависимости от состояния текстового поля. Селектор — это то, что соединяет и следующий после него в HTML-коде и расположенный на том же уровне. Когда это CSS-правило становится активным, подпись к полю меняет свой внешний вид: перемещается и масштабируется. Т.е. покидает поле ввода и не мешает пользователю печатать в нём.

Чтобы оживить переход состояния метки, можно добавить такой переход.

Лучше этот переход разделить на два и таким образом выделять метку, когда фокус переместится в поле ввода текста. Всегда полезно дать пользователю визуальную подсказку о том, где находятся курсор и фокус. Курсор во многих случаях слишком тонкий, поэтому уделить больше внимания тому факту, что фокус перемещен в поле для ввода не повредит.

HTML TextArea maxlength

Do You know? You can set the limit of TextArea by using the HTML TextArea maxlength attribute.

See below example code line. By adding maxlength attribute with the value it 10, then only 10 characters the user can enter.

Disabled

Is it possible to do HTML Textarea disabled? Yes by using a Disabled attribute in a tag like – <textarea disabled>.

See Below for example code line. After this, a TextArea is not editable. A User can edit or enter any value.

TextArea resize

At the left-bottom TextArea resize optionally available. Where users can easily increase the size of it.

You can do the HTML textarea size property fixed by using CSS code in element- style=”resize:none”

Output: See GIF with and without resize option TextArea box.

Attributes | Important

Below is Addtional HTML textarea attributes, which you can use in TextArea Input Tag.

Attribute Value Description
autofocus autofocus Specifies that a text area should automatically get focus when the page loads
cols number Specifies the visible width of a text area
dirname textareaname.dir Specifies that the text direction of the textarea will be submitted
disabled disabled Specifies that a text area should be disabled
form form_id Specifies one or more forms the text area belongs to
maxlength number Specifies the maximum number of characters allowed in the text area
name text Specifies a name for a text area
placeholder text Specifies a short hint that describes the expected value of a text area
readonly readonly Specifies that a text area should be read-only
required required Specifies that a text area is required/must be filled out
rows number Specifies the visible number of lines in a text area
wrap hardsoft Specifies how the text in a text area is to be wrapped when submitted in a form

HTML Textarea Width and Height | How to

To set an HTML TextArea Height and Width you can use cols and rows attributes with CSS code or else only use CSS.

See the below example of it. Using inline CSS style.

Output:

So you now understand the why HTML TextArea Required in Web App. If you have any doubt and suggestion. Then comment on it.

Атрибуты rows и cols тега

Для того, чтобы задать ширину и высоту поля, используются
атрибуты cols и rows.
Атрибут cols принимает в качестве значения натуральные числа, которые определяют ширину текстового поля в виде
количества символов моноширинного шрифта. По умолчанию принимает значение «20». Поскольку ширина текстового поля
«textarea» зависит от текущего размера шрифта, то с увеличением или уменьшением размера шрифта будет изменяться и
ширина поля в пикселях. Атрибут rows задает высоту текстового поля в строках (без прокрутки) и принимает в качестве
значения натуральные числа. По умолчанию принимает значение «2». Опять же, при изменении размера шрифта, изменяется
и высота поля в пикселах.

Select

На HTML страничку селекты выводятся так:

<select>
	<option value="">Укажите возраст</option>
	<option value="0 - 12 месяцев">0 - 12 месяцев</option>
	<option value="1 - 3 года">1 - 3 года</option>
	<option value="3 - 5 лет">3 - 5 лет</option>
	<option value="Больше 5 лет">Больше 5 лет</option>
</select>

Реально кучу плагинов jQuery для их стилизации, но мой метод я считаю самый правильный, суть его такая же как и в случае с radio кнопками, только здесь вместо дивов будет использоваться список, который выпадает по клику на ссылку, а потом при клике на ссылку из выпадающего списка ее текстовое значение будет заносится в скрытый инпут и в первую ссылку по которой кликнули. Все очень просто)))

HTML рзаметка выглядит следующим образом:

<div class="select">
	<a href="javascript:void(0);" class="slct">Выберите Ваше лучшее качество:</a>
	<ul class="drop">
		<li><a href="">Красивый(ая)</a></li>
		<li><a href="">Умный(ая)</a></li>
		<li><a href="">Коммуникабульный(ая)</a></li>
		<li><a href="">Скромный(ая)</a></li>
	</ul>
	<input type="hidden" id="select" />
</div>

Теперь добавим стилей для всего этого дела

/*	=	Select */
.slct {
	display: block;
	border-radius: 5px;
	border: 1px solid #cecece;
	background-color: #F6F6f6;
	width: 285px;
	padding: 4px 15px 4px 10px;
	color: #444;
	background-position: 290px -145px;

	/*
		Супер финт обрезаем текст
		чтобы не вылезал за рамку
	*/
	overflow: hidden;
	white-space:nowrap;
	text-overflow: ellipsis;
	-o-text-overflow: ellipsis;	

}
.slct.active {
	border-radius: 5px 5px 0 0;
	border-bottom: none;
}
.drop {
	margin: 0;
	padding: 0;
	width: 310px;
	border: 1px solid #cecece;
	border-top: none;
	display: none;
	position: absolute;
	background: #fff;
}
.drop li {
	list-style: none;
	border-top: 1px dotted #e8e8e8;
	cursor: pointer;
	display: block;
	color: #444;
	padding: 4px 15px 4px 25px;
	background-position: 10px -119px;
}
.drop li:hover {
	background-color: #e8e8e8;
	color: #222;
}

ну и без jQuery опять никуда:

// Select
$('.slct').click(function(){
	/* Заносим выпадающий список в переменную */
	var dropBlock = $(this).parent().find('.drop');

	/* Делаем проверку: Если выпадающий блок скрыт то делаем его видимым*/
	if( dropBlock.is(':hidden') ) {
		dropBlock.slideDown();

		/* Выделяем ссылку открывающую select */
		$(this).addClass('active');

		/* Работаем с событием клика по элементам выпадающего списка */
		$('.drop').find('li').click(function(){

			/* Заносим в переменную HTML код элемента
			списка по которому кликнули */
			var selectResult = $(this).html();

			/* Находим наш скрытый инпут и передаем в него
			значение из переменной selectResult */
			$(this).parent().parent().find('input').val(selectResult);

			/* Передаем значение переменной selectResult в ссылку которая
			открывает наш выпадающий список и удаляем активность */
			$(this).parent().parent().find('.slct').removeClass('active').html(selectResult);

			/* Скрываем выпадающий блок */
			dropBlock.slideUp();
		});

	/* Продолжаем проверку: Если выпадающий блок не скрыт то скрываем его */
	} else {
		$(this).removeClass('active');
		dropBlock.slideUp();
	}

	/* Предотвращаем обычное поведение ссылки при клике */
	return false;
});

Дальше займемся кнопками загрузить изображение и кнопкой отправкой формы.

HTML Справочник

HTML Теги по алфавитуHTML Теги по категорииHTML ПоддержкаHTML АтрибутыHTML ГлобальныеHTML СобытияHTML Названия цветаHTML ХолстHTML Аудио/ВидеоHTML ДекларацииHTML Набор кодировокHTML URL кодHTML Коды языкаHTML Коды странHTTP СообщенияHTTP методыКовертер PX в EMКлавишные комбинации

HTML Теги

<!—…—>
<!DOCTYPE>
<a>
<abbr>
<acronym>
<address>
<applet>
<area>
<article>
<aside>
<audio>
<b>
<base>
<basefont>
<bdi>
<bdo>
<big>
<blockquote>
<body>
<br>
<button>
<canvas>
<caption>
<center>
<cite>
<code>
<col>
<colgroup>
<data>
<datalist>
<dd>
<del>
<details>
<dfn>
<dialog>
<dir>
<div>
<dl>
<dt>
<em>
<embed>
<fieldset>
<figcaption>
<figure>
<font>
<footer>
<form>
<frame>
<frameset>
<h1> — <h6>
<head>
<header>
<hr>
<html>
<i>
<iframe>
<img>
<input>
<ins>
<kbd>
<label>
<legend>
<li>
<link>
<main>
<map>
<mark>
<meta>
<meter>
<nav>
<noframes>
<noscript>
<object>
<ol>
<optgroup>
<option>
<output>
<p>
<param>
<picture>
<pre>
<progress>
<q>
<rp>
<rt>
<ruby>
<s>
<samp>
<script>
<section>
<select>
<small>
<source>
<span>
<strike>
<strong>
<style>
<sub>
<summary>
<sup>
<svg>
<table>
<tbody>
<td>
<template>
<textarea>
<tfoot>
<th>
<thead>
<time>
<title>
<tr>
<track>
<tt>
<u>
<ul>
<var>
<video>
<wbr>

Conclusion

To conclude, we can say that it is pretty easy and comfortable to create and style a textarea element in HTML5 and CSS3.

Do always remember to give the textarea a when considering information that has to be submitted like so:

<!-- HTML SECTION  -->
<form action="/post">
	<textarea name="message" placeholder="Write your message here..."></textarea>
	<input type="submit"> <!-- this represents the submit button -->
</form>

The code above is an example of how you can have a textarea inside a form and submit it.

Also, take advantage of the html attributes to achieve as much as you can without having to style it all in css.

However, styling works just good for elements of html directly as well as when referred to classes.

HTML Теги

<!—…—><!DOCTYPE><a><abbr><acronym><address><applet><area><article><aside><audio><b><base><basefont><bdi><bdo><big><blockquote><body><br><button><canvas><caption><center><cite><code><col><colgroup><data><datalist><dd><del><details><dfn><dialog><dir><div><dl><dt><em><embed><fieldset><figcaption><figure><font><footer><form><frame><frameset><h1> — <h6><head><header><hr><html><i><iframe><img><input><ins><kbd><label><legend><li><link><main><map><mark><meta><meter><nav><noframes><noscript><object><ol><optgroup><option><output><p><param><picture><pre><progress><q><rp><rt><ruby><s><samp><script><section><select><small><source><span><strike><strong><style><sub><summary><sup><svg><table><tbody><td><template><textarea><tfoot><th><thead><time><title><tr><track><tt><u><ul><var><video>

Как добавить стиль к тегу ?

Цвет текста внутри тега <textarea>:

  • CSS свойство color определяет цвет контента и оформления текста.
  • CSS свойство background-color устанавливает фоновый цвет элемента.

Стили форматирования текста для тега <textarea>:

  • CSS свойство text-indent указывает размер отступа первой строки в текстовом блоке.
  • CSS свойство text-overflow указывает, как будет отображаться пользователю строчный текст, выходящий за границы блока.
  • CSS свойство white-space указывает, как будут отображены пробелы внутри элемента.
  • CSS свойство word-break указывает перенос строки.

Другие свойства для тега <textarea>:

Стиль с CSS

— замещаемый элемент — он имеет внутренние размеры, как растровое изображение. По умолчанию его значение — . По сравнению с другими элементами формы, его относительно легко стилизовать, с его блочной моделью, шрифтами, цветовой схемой и т. Д. Легко манипулировать с помощью обычного CSS.

Стилизация HTML-форм дает несколько полезных советов по стилизации .

Базовое несоответствие

Спецификация HTML не определяет, где находится базовая линия , поэтому разные браузеры устанавливают ее в разные позиции. Для Gecko базовая линия устанавливается на базовой линии первой строки текстового поля, в другом браузере она может быть установлена ​​в нижней части поля . Не используйте на нем ; поведение непредсказуемо.

Управление масштабируемостью тестареа

В большинстве браузеров, s является изменяемым — вы заметите перетащить ручку в правом угле, который может быть использован для изменения размера элемента на странице. Это контролируется свойством CSS — изменение размера включено по умолчанию, но вы можете явно отключить его, используя для значение :

textarea {
  resize: none;
}

Стилизация действительных и недействительных значений

Допустимые и недопустимые значения элемента (например, те, которые находятся в пределах и за пределами границ, установленных параметрами , или ), могут быть выделены с помощью псевдоклассов и . Например, чтобы дать вашему текстовому полю различную границу в зависимости от того, действительное оно или недействительное:

textarea:invalid {
  border: 2px dashed red;
}

textarea:valid {
   border: 2px solid lime;
}

Input

В HTML его выводят вот таким способом:

<input type="text" id="text" name="text" value="some text" />

Обязательным параметром тега input является атрибут type (тип, это может быть текст , кнопка отправки , скрытое поле , переключатель , чекбокс , загрузка файла).

Для стилизации этого тега jQuery не требуется, главное помнить, что браузеры неоднозначно работают с его высотой, поэтому высоту этого элемента стоит подбирать исходя из размера шрифта, который Вы будете использовать и чтобы слова не чёркали по рамке нужно добавлять отступ (padding)

input {
	width: 300px;
	font-size: 13px;
	padding: 6px 0 4px 10px;
	border: 1px solid #cecece;
	background: #F6F6f6;
	border-radius: 8px;
}

Иногда для Internet Explorer 8 нужно увеличить высоту на 1px, чтобы тег соответствовал дизайну, тогда в стилях нужно добавить хак для IE:

input {
	padding-bottom: 5px\0;
}

Вот и все тайны связанные с этим тегом. Дальше рассмотри тег для ввода нескольких строк текста textarea.

Code Example

What is Used For?

HTML5 Textarea Attributes

HTML5 introduced a few new attributes which can be used with textarea elements. Here are some of the most important:

  • : Associates the textarea with a form. Use the ID attribute of the form as the value for the textarea form attributes. This allows you to place a textarea anywhere on a webpage, even outside of the form element, and still have the contents of the textarea included when the form is submitted.
  • and : Used to specify a minimum or maximum number of characters that may be entered into a textarea.
  • : Adds placeholder text to the textarea that disappears as soon as a user places the cursor inside of the element.
  • : Requires that the textarea contain content prior to allowing form submission.
  • : Specifies whether or not hard-returns should be added to the content submitted in a textarea.

Attributes in Action

Here’s an example of how some of these new attributes can be used to control the behavior of a textarea.

If we pair those textarea elements with a simple script and button element, we get the following form:

Adam Wood

Creating a simple element

There are two ways to create a very basic textarea: using only Javascript and using the <textarea> tag. Let’s see them both in action below!

4.1 Using Javascript

To create a textarea using strictly plain Javascript we would only need the function which does this and something to trigger it’s execution, which can be either a button being pressed or anything, really. As usual, we will separate the Javascript and HTML parts of our code, even though in our case it’s not strictly necessary. That’s because it’s good programming practice in case you have large chunks of code to deal with!

The heart of it, of course, would be the Javascript code, which we will place in a separate file named simply like below, without any tags or anything else. Just the code!

textarea.js

function createOurTextarea() {
    var ourElement = document.createElement("TEXTAREA");
    var ourElementText = document.createTextNode("This is our TextArea!");
    ourElement.appendChild(ourElementText);
    document.body.appendChild(ourElement);
}

It is pretty simple to understand what we’ve done here: We create a textarea element, create a text node for it and append it to the first one, and lastly, append these two both to the document body. All this is wrapped into a function, which we will use to trigger the textarea. We would do that by clicking a button which fires this function as soon as it’s clicked. The HTML code would go like below:

textarea.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Textarea</title>
    <script src="textarea.js" type="text/javascript"></script>
</head>
<body>

<button onclick="createOurTextarea()">Create TextArea</button>

</body>
</html>

There you have it!

4.2 Using the <textarea> tag

I think that all would agree with me in saying that the easiest way to create a textarea element would be through using the tag and some of the attributes for this element according to the needs we have. Of course, later on we can add more functionality to it using Javascript functions, but for now, to create it, we would only need the code snippet below:

textarea.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Textarea</title>
    <script src="textarea.js" type="text/javascript"></script>
</head>
<body>

<textarea name="comments" cols="40" rows="6"></textarea> 

<p><input type=SUBMIT value="submit"></p>

</body>
</html>

As you can see, we only used the tag together with three of the attributes explained above: , and . Also, we used a submit button, which we do not strictly need for the textarea, but is usually there to submit the info. However, usually we only have one submit button for all the form.

Гость форума
От: admin

Эта тема закрыта для публикации ответов.