Свойства и методы формы
Формы и элементы управления, такие как <input> , имеют множество специальных свойств и событий.
Работать с формами станет намного удобнее, когда мы их изучим.
Навигация: формы и элементы
Формы в документе входят в специальную коллекцию document.forms .
Это так называемая «именованная» коллекция: мы можем использовать для получения формы как её имя, так и порядковый номер в документе.
Когда мы уже получили форму, любой элемент доступен в именованной коллекции form.elements .
Может быть несколько элементов с одним и тем же именем, это часто бывает с кнопками-переключателями radio .
В этом случае form.elements[name] является коллекцией, например:
Эти навигационные свойства не зависят от структуры тегов внутри формы. Все элементы управления формы, как бы глубоко они не находились в форме, доступны в коллекции form.elements .
Форма может содержать один или несколько элементов <fieldset> внутри себя. Они также поддерживают свойство elements , в котором находятся элементы управления внутри них.
Есть более короткая запись: мы можем получить доступ к элементу через form[index/name] .
Другими словами, вместо form.elements.login мы можем написать form.login .
Это также работает, но есть небольшая проблема: если мы получаем элемент, а затем меняем его свойство name , то он всё ещё будет доступен под старым именем (также, как и под новым).
В этом легче разобраться на примере:
Обычно это не вызывает проблем, так как мы редко меняем имена у элементов формы.
Обратная ссылка: element.form
Для любого элемента форма доступна через element.form . Так что форма ссылается на все элементы, а эти элементы ссылаются на форму.
Элементы формы
Рассмотрим элементы управления, используемые в формах.
input и textarea
К их значению можно получить доступ через свойство input.value (строка) или input.checked (булево значение) для чекбоксов.
Обратим внимание: хоть элемент <textarea>. </textarea> и хранит своё значение как вложенный HTML, нам не следует использовать textarea.innerHTML для доступа к нему.
Там хранится только тот HTML, который был изначально на странице, а не текущее значение.
select и option
Элемент <select> имеет 3 важных свойства:
- select.options – коллекция из подэлементов <option> ,
- select.value – значение выбранного в данный момент <option> ,
- select.selectedIndex – номер выбранного <option> .
Они дают три разных способа установить значение в <select> :
- Найти соответствующий элемент <option> и установить в option.selected значение true .
- Установить в select.value значение нужного <option> .
- Установить в select.selectedIndex номер нужного <option> .
Первый способ наиболее понятный, но (2) и (3) являются более удобными при работе.
Вот эти способы на примере:
В отличие от большинства других элементов управления, <select> позволяет нам выбрать несколько вариантов одновременно, если у него стоит атрибут multiple . Эту возможность используют редко, но в этом случае для работы со значениями необходимо использовать первый способ, то есть ставить или удалять свойство selected у подэлементов <option> .
Их коллекцию можно получить как select.options , например:
new Option
Элемент <option> редко используется сам по себе, но и здесь есть кое-что интересное.
В спецификации есть красивый короткий синтаксис для создания элемента <option> :
- text – текст внутри <option> ,
- value – значение,
- defaultSelected – если true , то ставится HTML-атрибут selected ,
- selected – если true , то элемент <option> будет выбранным.
Тут может быть небольшая путаница с defaultSelected и selected . Всё просто: defaultSelected задаёт HTML-атрибут, его можно получить как option.getAttribute(‘selected’) , а selected – выбрано значение или нет, именно его важно поставить правильно. Впрочем, обычно ставят оба этих значения в true или не ставят вовсе (т.е. false ).
Тот же элемент, но выбранный:
Элементы <option> имеют свойства:
option.selected Выбрана ли опция. option.index Номер опции среди других в списке <select> . option.value Значение опции. option.text Содержимое опции (то, что видит посетитель).
Ссылки
- Спецификация: https://html.spec.whatwg.org/multipage/forms.html.
Итого
Свойства для навигации по формам:
document.forms Форма доступна через document.forms[name/index] . form.elements Элементы формы доступны через form.elements[name/index] , или можно просто использовать form[name/index] . Свойство elements также работает для <fieldset> . element.form Элементы хранят ссылку на свою форму в свойстве form .
Значения элементов формы доступны через input.value , textarea.value , select.value и т.д. либо input.checked для чекбоксов и переключателей.
Для элемента <select> мы также можем получить индекс выбранного пункта через select.selectedIndex , либо используя коллекцию пунктов select.options .
Это были основы для начала работы с формами. Далее в учебнике мы встретим ещё много примеров.
В следующей главе мы рассмотрим такие события, как focus и blur , которые могут происходить на любом элементе, но чаще всего обрабатываются в формах.
Convert Form Data to JavaScript Object
When working with forms in JavaScript, you'll typically need to convert form data to a JavaScript object (JSON) in order to populate an array, database, local storage, send it to an API, or even consume the data in your application. Conversion between form data and JSON is one of the most common ways to process form data as it opens doors to a plethora of other uses for that data.
In this article, we'll take a look at how to easily convert form data into a JavaScript object without installing any unnecessary dependencies. We'll achieve that just by using the FormData API — a built-in browser API used to get form values as JavaScript objects.
Note: This app is available as a demo on CodePen.
Let's get started by creating a simple HTML form containing several common form fields — two input fields, a text area, and a submit button:
Now, we can take a look at how to convert its data into JSON (JavaScript Object Notation) using FormData API.
FormData API
FormData is a built-in browser API that provides us a way to easily access any field from a HTML form. The first step in using FormData API is to obtain the form element using some of the appropriate HTML DOM methods — document.querySelector() or document.getElementById() . After that, we can add an event listener that calls callbackFunction when it registers a submit event on the form:
For the event listener to work, we must define the function that will handle the submit event. For now, let's just make it create the FormData object and log its content into console:
Note: We used the preventDefault() to prevent the form from reloading after the submit button is clicked — which is the default behavior. This is a sensible default, but for the sake of illustration in our app — we'll prevent it and display the data on the right-hand div.
When you run the code above, the result will be an empty object, which is not what we've expected:
Even though it may seem like we've created an empty object, that is not the case. That FormData object has a key-value pair for each field in our form — therefore, we need to iterate over all those pairs and store them in a separate object. After that, we can use that object to access each individual field of our form.
There are two major ways we can get data from the FormData API — one is to loop through every key-value pair, and the other is to use the Object.fromEntries() method.
How to Convert Form Data to JSON With Loops
The first way to create a readable object from a FormData object is to iterate over its key-value pairs and manually add keys and values to the newly created object. For the purpose of this article, we'll use the forEach() loop in JavaScript. First of all, we'll create an empty object and then iterate over the FormData object we've created in the previous section:
Note: The forEach() method is not async friendly, if you need your callback function to support async calls — you should use the for-of loop.
At this point we can modify the callbackFunction() from the previous section so that it correctly outputs the form data as an object:
Now, when we fill out our form and click the submit button we should have the following output:
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
This object has field names as its keys and corresponding field values as its values.
How to Convert Form Data to JSON With Object.fromEntries()
Alternatively, we can use the Object.fromEnteries() method instead of loops to retrieve form fields from the FormData object. That way we don't need to create an empty object before we start — the method allows us to directly convert the FormData object to the corresponding JavaScript object:
At this point, our modified callback function will look like this:
An object populated using Object.fromEnteries() will have names of the form fields as its keys and corresponding form values as its values:
Note: For both methods, we can use JSON.stringify() to convert the object into a JSON string, which we can then use to send JSON encoded data to APIs.
How to Get Multiple Selected Values in JSON With The FormData API
The above methods are compatible with almost all form fields — input text, number, radio, select. However, there are other fields that can be a bit more tricky to work with. The most notable one is the checkbox — it allows multiple values to be selected. But the previously shown methods will replace all of those selected values with just one — which is ultimately stored in the resulting object. Let's take a look at how to solve that and store all selected values in the resulting object. Suppose we have an HTML form with a checkbox field:
We can get all the selected data into an array using the getAll() method on the FormData object:
At this point, our code will look something like this:
And the populated object will contain an array of values a user selected in the checkbox field:
Note: You can check out this live demo on CodePen which uses all the major form field types and generates the data as a JavaScript object when submitted.
Conclusion
In this article, we've taken a look at how to use the FormData API to convert form data to JavaScript objects without any additional dependencies. We've also learned how to correctly handle various types of form fields (inputs, text-areas, etc.), as well as some trickier ones such as checkboxes.
JavaScript Form
Summary: in this tutorial, you will learn about JavaScript form API: accessing the form, getting values of the elements, validating form data, and submitting the form.
Form basics
To create a form in HTML, you use the <form> element:
The <form> element has two important attributes: action and method .
- The action attribute specifies a URL that will process the form submission. In this example, the action is the /signup URL.
- The method attribute specifies the HTTP method to submit the form with. Usually, the method is either post or get .
Generally, you use the get method when you want to retrieve data from the server and the post method when you want to change data on the server.
JavaScript uses the HTMLFormElement object to represent a form. The HTMLFormElement has the following properties that correspond to the HTML attributes:
- action – is the URL that processes the form data. It is equivalent to the action attribute of the <form> element.
- method – is the HTTP method which is equivalent to the method attribute of the <form> element.
The HTMLFormElement element also provides the following useful methods:
- submit() – submit the form.
- reset() – reset the form.
Referencing forms
To reference the <form> element, you can use DOM selecting methods such as getElementById() :
An HTML document can have multiple forms. The document.forms property returns a collection of forms ( HTMLFormControlsCollection ) on the document:
To reference a form, you use an index. For example, the following statement returns the first form of the HTML document:
Submitting a form
Typically, a form has a submit button. When you click it, the browser sends the form data to the server. To create a submit button, you use <input> or <button> element with the type submit :
If the submit button has focus and you press the Enter key, the browser also submits the form data.
When you submit the form, the submit event is fired before the request is sent to the server. This gives you a chance to validate the form data. If the form data is invalid, you can stop submitting the form.
To attach an event listener to the submit event, you use the addEventListener() method of the form element as follows:
To stop the form from being submitted, you call the preventDefault() method of the event object inside the submit event handler like this:
Typically, you call the event.preventDefault() method if the form data is invalid. To submit the form in JavaScript, you call the submit() method of the form object:
Note that the form.submit() does not fire the submit event. Therefore, you should always validate the form before calling this method.
Accessing form fields
To access form fields, you can use DOM methods like getElementsByName() , getElementById() , querySelector() , etc.
Also, you can use the elements property of the form object. The form.elements property stores a collection of the form elements.
JavaScript allows you to access an element by index, id, or name. Suppose that you have the following signup form with two <input> elements:
To access the elements of the form, you get the form element first:
And use index, id, or name to access the element. The following accesses the first form element:
The following accesses the second input element:
After accessing a form field, you can use the value property to access its value, for example:
Put it all together: signup form
The following illustrates the HTML document that has a signup form. See the live demo here.
The HTML document references the style.css and app.js files. It uses the <small> element to display an error message in case the <input> element has invalid data.
Submitting the form without providing any information will result in the following error:
Submitting the form with the name but invalid email address format will result in the following error:
The following shows the complete app.js file:
The showMessage() function
The showMessage() function accepts an input element, a message, and a type:
The following shows the name input field on the form:
If the name’s value is blank, you need to get its parent first which is the <div> with the class “field”.
Next, you need to select the <small> element:
Then, update the message:
After that, we change the CSS class of the input field based on the value of the type parameter. If the type is true, we change the class of the input to success. Otherwise, we change the class to error.
Finally, return the value of the type:
The showError() and showSuccess() functions
The the showError() and showSuccess() functions call the showMessage() function. The showError() function always returns false whereas the showSuccess() function always returns true . Also, the showSuccess() function sets the error message to an empty string.
The hasValue() function
The hasValue() function checks if an input element has a value or not and show an error message using the showError() or showSuccess() function accordingly:
The validateEmail() function
The validateEmail() function validates if an email field contains a valid email address:
The validateEmail() function calls the hasValue() function to check if the field value is empty. If the input field is empty, it shows the requiredMsg .
To validate the email, it uses a regular expression. If the email is invalid, the validateEmail() function shows the invalidMsg .
The submit event handler
First, select the signup form by its id using the querySelector() method:
Second, define some constants to store the error messages:
Third, add the submit event listener of the signup form using the addEventListener() method:
JavaScript Формы
Цель работы: научиться управлять формой через сценарий.
Форма служит для ввода пользователем через окно браузера данных и передачи их на веб-сервер. Форма состоит из контейнера <FORM> …</form> и заключённых в него тегов (элементов) <INPUT>, <SELECT> и <TEXTAREA>.
Проверка данных перед отправкой на сервер
Для уменьшения нагрузки на сеть и веб-сервер можно проверять введённые пользователем данные на браузере с помощью сценария на JavaScript. Если в данных обнаружится ошибка, то пользователю предоставляется возможность её исправить. Введенные правильно данные отправляются на веб-сервер. Использование сценария для управления формой демонстрируется в примере 3.1.
Пример 3.1
Пример 3.1 состоит из двух страниц.Первая страница служит для ввода пользователем данных и их проверки с помощью скрипта, написанного на JavaScript. Если данные введены правильно, то они отправляются на веб-сервер. На веб-сервере полученные данные обрабатываются скриптом, написанным на языке PHP, формируется и пересылается на браузер пользователя новая страница.
В скрипте,написанном на JavaScript, для доступа к данным, находящимся в форме, используются имена и индексы элементов формы. Для задания адреса (URL) страницы, содержащей PHP-скрипт, используется свойствоaction объекта Form.
Получение данных из всплывающего списка
Иногда можно полностью решать задачу ведения диалога с пользователем средствами JavaScript, не обращаясь к веб-серверу. В примере 3.2 пользователь вводит код цвета в модели RGB и выбирает из списка название цвета. После нажатия кнопки Ввод на экран выводятся окрашенные в выбранные цвета код и название цвета.
Пример 3.2
В примере 3.2 нет необходимости использовать контейнер <FORM> …</form>, так как на веб-сервер ничего не передаётся. Для вывода на экран кода и названия цвета используется свойство innerHTML. Строго говоря, innerHTML следовало бы называть не свойством, а методом. Рассмотрим применение этого свойства на примере вывода на экран введённого пользователем кода цвета. Пусть пользователь ввёл код цвета a=FF0000, т.е. красный.
В результате выполнения оператора
e=»<FONT size=7 color=FF0000>FF0000</font>»
В результате выполнения оператора
в элемент <B ></b> вставится значение переменной e:
и браузер выполнит преобразованный злемент (оператор языка HTML), т.е. выведет на экран
FF0000
Таким образом, с помощью свойства innerHTML можно на стороне браузера программным путём вносить изменения в HTML-документ (страницу сайта).
Задача 3.1. Создайте сайт из двух страниц. Первая страница имеет заголовок Заказ мебели. На ней расположены два поля со списками (теги <SELECT>), поле (<INPUT>) и кнопка (<SUBMIT>). Из первого поля со списком пользователь выбирает изделие (шкаф, стол, сервант и т.д.).Из второго поля со спискомпользователь выбирает материал (дуб,орех, бук). В третье поле нужно ввести количество заказываемых изделий. После ввода данных необходимо проверить, все ли данные введены.Если обнаружена ошибка, то нужно вывести сообщение и предложить её исправить.
Проверка данных сразу после ввода
Если в форме нужно заполнить много полей, то пользователю удобно получать сообщения об ошибках сразу после окончания ввода данных в очередное поле, то есть после нажатия клавиши Tab или клавиши со стрелкой. Для немедленной проверки введённых данных служит событие onchange:
<INPUT TYPE =»text»SIZE=6 onchange=»arg(this)»>
Функция, вызываемая событием onchange, имеет примерно такую структуру:
Методы focus() и select() служат для возвращения курсора мышки в поле ввода и выделения ошибочных данных. Эти методы без использования специальных приёмов правильно работают только в браузере Mozilla.
Задача 3.2. Создайте страницу (рис. 1) для вычисления тригонометрических функций. Вводимые пользователем данные должны проверяться немедленно после ввода и после нажатия кнопки Вычислить.
Указания. Не забудьте перевести градусы в радианы. Название тригонометрической функции можно передавать как параметр тега :
Сформируйте текстовую строку вида
Затем воспользуйтесь функцией eval(строка), которая выполняет выражение, хранящееся в строке.