Javascript присвоить значение форме

Form properties and methods

Forms and control elements, such as have a lot of special properties and events.

Working with forms will be much more convenient when we learn them.

Document forms are members of the special collection document.forms .

That’s a so-called “named collection”: it’s both named and ordered. We can use both the name or the number in the document to get the form.

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 .

    

There may be multiple elements with the same name. This is typical with radio buttons and checkboxes.

In that case, form.elements[name] is a collection. For instance:

    

These navigation properties do not depend on the tag structure. All control elements, no matter how deep they are in the form, are available in form.elements .

A form may have one or many elements inside it. They also have elements property that lists form controls inside them.

  
info

There’s a shorter notation: we can access the element as form[index/name] .

In other words, 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:

   

That’s usually not a problem, however, 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.

   

Form elements

Let’s talk about form controls.

input and textarea

We can access their value as input.value (string) or input.checked (boolean) for checkboxes and radio buttons.

input.value = "New value"; textarea.value = "New text"; input.checked = true; // for a checkbox or radio button

Please note that even though holds its value as nested HTML, we should never use textarea.innerHTML to access it.

It stores only the HTML that was initially on the page, not the current value.

select and option

A element has 3 important properties:

  1. select.options – the collection of subelements,
  2. select.value – the value of the currently selected ,
  3. select.selectedIndex – the number of the currently selected .

They provide three different ways of setting a value for a :

  1. Find the corresponding element (e.g. among select.options ) and set its option.selected to true .
  2. If we know a new value: set select.value to the new value.
  3. If we know the new option number: set select.selectedIndex to that number.

Here is an example of all three methods:

  

Unlike most other controls, allows to select multiple options at once if it has multiple attribute. This attribute is rarely used, though.

For multiple selected values, use the first way of setting values: add/remove the selected property from subelements.

Here’s an example of how to get selected values from a multi-select:

   

new Option

In the specification there’s a nice short syntax to create an element:

option = new Option(text, value, defaultSelected, selected);

This syntax is optional. We can use document.createElement(‘option’) and set attributes manually. Still, it may be shorter, so here are the parameters:

  • text – the text inside the option,
  • value – the option value,
  • defaultSelected – if true , then selected HTML-attribute is created,
  • selected – if true , then the option is selected.

The difference between defaultSelected and selected is that defaultSelected sets the HTML-attribute (that we can get using option.getAttribute(‘selected’) , while selected sets whether the option is selected or not.

In practice, one should usually set both values to true or false . (Or, simply omit them; both default to false .)

For instance, here’s a new “unselected” option:

let option = new Option("Text", "value"); // creates 

The same option, but selected:

let option = new Option("Text", "value", true, true);

Option elements have properties:

option.selected Is the option selected. option.index The number of the option among the others in its . option.text Text content of the option (seen by the visitor).

References

Summary

document.forms A form is available as document.forms[name/index] . form.elements Form elements are available as form.elements[name/index] , or can use just form[name/index] . The elements property also works for . element.form Elements reference their form in the form property.

Value is available as input.value , textarea.value , select.value , etc. (For checkboxes and radio buttons, use input.checked to determine whether a value is selected.)

For , one can also get the value by the index select.selectedIndex or through the options collection select.options .

These are the basics to start working with forms. We’ll meet many examples further in the tutorial.

In the next chapter we’ll cover focus and blur events that may occur on any element, but are mostly handled on forms.

Источник

Свойства и методы формы

Формы и элементы управления, такие как , имеют множество специальных свойств и событий.

Работать с формами станет намного удобнее, когда мы их изучим.

Формы в документе входят в специальную коллекцию document.forms .

Это так называемая «именованная» коллекция: мы можем использовать для получения формы как её имя, так и порядковый номер в документе.

document.forms.my - форма с именем "my" (name="my") document.forms[0] - первая форма в документе

Когда мы уже получили форму, любой элемент доступен в именованной коллекции form.elements .

    

Может быть несколько элементов с одним и тем же именем, это часто бывает с кнопками-переключателями radio .

В этом случае form.elements[name] является коллекцией, например:

    

Эти навигационные свойства не зависят от структуры тегов внутри формы. Все элементы управления формы, как бы глубоко они не находились в форме, доступны в коллекции form.elements .

Форма может содержать один или несколько элементов внутри себя. Они также поддерживают свойство elements , в котором находятся элементы управления внутри них.

  
info

Есть более короткая запись: мы можем получить доступ к элементу через form[index/name] .

Другими словами, вместо form.elements.login мы можем написать form.login .

Это также работает, но есть небольшая проблема: если мы получаем элемент, а затем меняем его свойство name , то он всё ещё будет доступен под старым именем (также, как и под новым).

В этом легче разобраться на примере:

   

Обычно это не вызывает проблем, так как мы редко меняем имена у элементов формы.

Обратная ссылка: element.form

Для любого элемента форма доступна через element.form . Так что форма ссылается на все элементы, а эти элементы ссылаются на форму.

   

Элементы формы

Рассмотрим элементы управления, используемые в формах.

input и textarea

К их значению можно получить доступ через свойство input.value (строка) или input.checked (булево значение) для чекбоксов.

input.value = "Новое значение"; textarea.value = "Новый текст"; input.checked = true; // для чекбоксов и переключателей

Обратим внимание: хоть элемент и хранит своё значение как вложенный HTML, нам не следует использовать textarea.innerHTML для доступа к нему.

Там хранится только тот HTML, который был изначально на странице, а не текущее значение.

select и option

Элемент имеет 3 важных свойства:

  1. select.options – коллекция из подэлементов ,
  2. select.value – значение выбранного в данный момент ,
  3. select.selectedIndex – номер выбранного .

Они дают три разных способа установить значение в :

  1. Найти соответствующий элемент и установить в option.selected значение true .
  2. Установить в select.value значение нужного .
  3. Установить в select.selectedIndex номер нужного .

Первый способ наиболее понятный, но (2) и (3) являются более удобными при работе.

Вот эти способы на примере:

  

В отличие от большинства других элементов управления, позволяет нам выбрать несколько вариантов одновременно, если у него стоит атрибут multiple . Эту возможность используют редко, но в этом случае для работы со значениями необходимо использовать первый способ, то есть ставить или удалять свойство selected у подэлементов .

Их коллекцию можно получить как select.options , например:

   

new Option

Элемент редко используется сам по себе, но и здесь есть кое-что интересное.

В спецификации есть красивый короткий синтаксис для создания элемента :

option = new Option(text, value, defaultSelected, selected);
  • text – текст внутри ,
  • value – значение,
  • defaultSelected – если true , то ставится HTML-атрибут selected ,
  • selected – если true , то элемент будет выбранным.

Тут может быть небольшая путаница с defaultSelected и selected . Всё просто: defaultSelected задаёт HTML-атрибут, его можно получить как option.getAttribute(‘selected’) , а selected – выбрано значение или нет, именно его важно поставить правильно. Впрочем, обычно ставят оба этих значения в true или не ставят вовсе (т.е. false ).

let option = new Option("Текст", "value"); // создаст 

Тот же элемент, но выбранный:

let option = new Option("Текст", "value", true, true);

option.selected Выбрана ли опция. option.index Номер опции среди других в списке . option.value Значение опции. option.text Содержимое опции (то, что видит посетитель).

Ссылки

Итого

Свойства для навигации по формам:

document.forms Форма доступна через document.forms[name/index] . form.elements Элементы формы доступны через form.elements[name/index] , или можно просто использовать form[name/index] . Свойство elements также работает для . element.form Элементы хранят ссылку на свою форму в свойстве form .

Значения элементов формы доступны через input.value , textarea.value , select.value и т.д. либо input.checked для чекбоксов и переключателей.

Для элемента мы также можем получить индекс выбранного пункта через select.selectedIndex , либо используя коллекцию пунктов select.options .

Это были основы для начала работы с формами. Далее в учебнике мы встретим ещё много примеров.

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

Источник

Читайте также:  Классы оболочки примитивных типов java
Оцените статью