# Form properties and methods [todo] Forms and control elements, such as `` have a lot of special properties and events. Working with forms can be much more convenient if we know them. [cut] ## Navigation: form and elements Document forms are members of the special collection `document.forms`. That's a *named* collection: we can use both the name and the number to get the form. ```js no-beautify document.forms.my - the form with name="my" document.forms[0] - the first form in the document ``` When we have a form, then any element is available in the named collection `form.elements`. For instance: ```html run height=40
``` There may be multiple elements with the same name, that's often the case with radio buttons. In that case `form.elements[name]` is a collection, for instance: ```html run height=40
``` These navigation properties do not depend on the tag structure. All elements, no matter how deep they are in the form, are available in `form.elements`. ````smart header="Fieldsets as \"subforms\"" A form may have one or many `
` elements inside it. They also support the `elements` property. For instance: ```html run height=80
info
``` ```` ````warn header="Shorter notation: `form.name`" There's a shorter notation: we can access the element as `form[index/name]`. Instead of `form.elements.login` we can write `form.login`. That also works, but there's a minor issue: if we access an element, and then change its `name`, then it is still available under the old name (as well as under the new one). That's easy to see in an example: ```html run height=40
``` That's usually not a problem, because we rarely change names of form elements. ```` ## Backreference: element.form For any element, the form is available as `element.form`. So a form references all elements, and elements reference the form. Here's the picture: ![](form-navigation.png) For instance: ```html run height=40
``` ## Values: input and textarea Normally, we can read the value as `input.value` or `input.checked` (for radio) Для большинства типов `input` значение ставится/читается через свойство `value`. ```js input.value = "Новое значение"; textarea.value = "Новый текст"; ``` ```warn header="Не используйте `textarea.innerHTML`" Для элементов `textarea` также доступно свойство `innerHTML`, но лучше им не пользоваться: оно хранит только HTML, изначально присутствовавший в элементе, и не меняется при изменении значения. ``` Исключения -- `input type="checkbox"` и `input type="radio"` **Текущее "отмеченное" состояние для `checkbox` и `radio` находится в свойстве `checked` (`true/false`).** ```js if (input.checked) { alert( "Чекбокс выбран" ); } ``` ## Элементы select и option Селект в JavaScript можно установить двумя путями: поставив значение `select.value`, либо установив свойство `select.selectedIndex` в номер нужной опции.: ```js select.selectedIndex = 0; // первая опция ``` Установка `selectedIndex = -1` очистит выбор. **Список элементов-опций доступен через `select.options`.** Если `select` допускает множественный выбор (атрибут `multiple`), то значения можно получить/установить, сделав цикл по `select.options`. При этом выбранные опции будут иметь свойство `option.selected = true`. Пример: ```html run
``` Спецификация: [the select element](https://html.spec.whatwg.org/multipage/forms.html#the-select-element). ````smart header="`new Option`" В стандарте [the option element](https://html.spec.whatwg.org/multipage/forms.html#the-option-element) есть любопытный короткий синтаксис для создания элемента с тегом `option`: ```js option = new Option(text, value, defaultSelected, selected); ``` Параметры: - `text` -- содержимое, - `value` -- значение, - `defaultSelected` и `selected` поставьте в `true`, чтобы сделать элемент выбранным. Его можно использовать вместо `document.createElement('option')`, например: ```js var option = new Option("Текст", "value"); // создаст ``` Такой же элемент, но выбранный: ```js var option = new Option("Текст", "value", true, true); ``` ```` ```smart header="Дополнительные свойства `option`" У элементов `option` также есть особые свойства, которые могут оказаться полезными (см. [the option element](https://html.spec.whatwg.org/multipage/forms.html#the-option-element)): `selected` : выбрана ли опция `index` : номер опции в списке селекта `text` : Текстовое содержимое опции (то, что видит посетитель). ``` ## Итого Свойства для навигации по формам: `document.forms` : Форму можно получить как `document.forms[name/index]`. `form.elements` : Элементы в форме: `form.elements[name/index]`. Каждый элемент имеет ссылку на форму в свойстве `form`. Свойство `elements` также есть у `
`. Значение элементов читается/ставится через `value` или `checked`. Для элемента `select` можно задать опцию по номеру через `select.selectedIndex` и перебрать опции через `select.options`. При этом выбранные опции (в том числе при мультиселекте) будут иметь свойство `option.selected = true`. Спецификация: [HTML5 Forms](https://html.spec.whatwg.org/multipage/forms.html).