Свойства и методы формы
Формы и элементы управления, такие как <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 , которые могут происходить на любом элементе, но чаще всего обрабатываются в формах.
Как взять значение из select js
In this article, we will learn to get the selected values in the dropdown list in Javascript. We can get the values using 2 methods:
- By using the value property
- By using selectedIndex property with the option property
We will understand both these methods through examples.
Method 1: Using the value property:
The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.
Syntax:
Example: This example describes the value property that can be found for the selected elements.
Output:
The selectedIndex property returns the index of the currently selected element in the dropdown list. This index starts from 0 and returns -1 if no option is selected. The options property returns the collection of all the option elements in the <select> dropdown list. The elements are sorted according to the source code of the page. The index found before it can be used with this property to get the selected element. This option’s value can be found by using the value property.
Syntax:
Property value:
- selectedIndex: It is used to set or get the index of the selected <option> element in the collection.
- length: It is read-only property that is used to get the number of <option> elements in the collection.
Return value: It returns HTMLOptionsCollection Object by specifying all the <option> elements in the <select> element. The element will be sorted in the collection
Example: This example describes the selectedIndex property with the option property.
JavaScript: How to Get the Value of a Select or Dropdown List
Getting the value of a select in HTML is a fairly recurring question. Learn how to return the value and text of a dropdown list using pure JavaScript or jQuery.
Let’s assume you have the following code:
- The value of the selected option.
- The text of the selected option.
How to get the value of a select
To get the value of a select or dropdown in HTML using pure JavaScript, first we get the select tag, in this case by id, and then we get the selected value through the selectedIndex property.
The value «en» will be printed on the console (Ctrl + Shift + J to open the console).
Getting the value of a select with jQuery
How to get the text of a select
To get the content of an option, but not the value, the code is almost the same, just take the text property instead of value.
The text «English» will be printed on the console (Ctrl + Shift + J to open the console).
Getting the text from a select with jQuery
Complete example
In the code below, when we change the dropdown value, the select value and text are shown in an input field.
Get selected value in dropdown list using JavaScript
How do I get the selected value from a dropdown list using JavaScript?
![]()
32 Answers 32
Given a select element that looks like this:
Running this code:
![]()
![]()
![]()
This is correct and should give you the value. Is it the text you’re after?
So you’re clear on the terminology:
This option has:
- Index = 0
- Value = hello
- Text = Hello World
The following code exhibits various examples related to getting/putting of values from input/select fields using JavaScript.


The following script is getting the value of the selected option and putting it in text box 1
The following script is getting a value from a text box 2 and alerting with its value
The following script is calling a function from a function
![]()
![]()
If you ever run across code written purely for Internet Explorer you might see this:
Running the above in Firefox et al will give you an ‘is not a function’ error, because Internet Explorer allows you to get away with using () instead of []:
The correct way is to use square brackets.
![]()
Any input/form field can use a “this” keyword when you are accessing it from inside the element. This eliminates the need for locating a form in the DOM tree and then locating this element inside the form.
![]()
![]()
There are two ways to get this done either using JavaScript or jQuery.
JavaScript:
OR
jQuery:
![]()
![]()
Beginners are likely to want to access values from a select with the NAME attribute rather than ID attribute. We know all form elements need names, even before they get ids.
So, I’m adding the getElementsByName() solution just for new developers to see too.
NB. names for form elements will need to be unique for your form to be usable once posted, but the DOM can allow a name be shared by more than one element. For that reason consider adding IDs to forms if you can, or be explicit with form element names my_nth_select_named_x and my_nth_text_input_named_y .
Example using getElementsByName :
$(‘#SelectBoxId option:selected’).text(); for getting the text as listed
$(‘#SelectBoxId’).val(); for getting the selected index value
![]()
I don’t know if I’m the one that doesn’t get the question right, but this just worked for me:
Use an onchange() event in your HTML, for example.
JavaScript
This will give you whatever value is on the select dropdown per click.
![]()
![]()
The previous answers still leave room for improvement because of the possibilities, the intuitiveness of the code, and the use of id versus name . One can get a read-out of three data of a selected option — its index number, its value and its text. This simple, cross-browser code does all three:
id should be used for make-up purposes. For functional form purposes, name is still valid, also in HTML5, and should still be used. Lastly, mind the use of square versus round brackets in certain places. As was explained before, only (older versions of) Internet Explorer will accept round ones in all places.
![]()
![]()
Another solution is:
![]()
![]()
The simplest way to do this is:
![]()
You can use querySelector .
E.g.
![]()
Running example of how it works:
Note: The values don’t change as the dropdown is changed, if you require that functionality then an onClick change is to be implemented.
To go along with the previous answers, this is how I do it as a one-liner. This is for getting the actual text of the selected option. There are good examples for getting the index number already. (And for the text, I just wanted to show this way)
In some rare instances you may need to use parentheses, but this would be very rare.
I doubt this processes any faster than the two line version. I simply like to consolidate my code as much as possible.
Unfortunately this still fetches the element twice, which is not ideal. A method that only grabs the element once would be more useful, but I have not figured that out yet, in regards to doing this with one line of code.
![]()
I have a bit different view of how to achieve this. I’m usually doing this with the following approach (it is an easier way and works with every browser as far as I know):
![]()
![]()
In 2015, in Firefox, the following also works.
e.options.selectedIndex
![]()
In more modern browsers, querySelector allows us to retrieve the selected option in one statement, using the :checked pseudo-class. From the selected option, we can gather whatever information we need:
event.target.value inside the onChange callback did the trick for me.
Most answers here get the value of the "this" select menu onchange by a plain text JavaScript selector.
This is not a DRY approach.
DRY (three lines of code):
Get the first select option:
With this idea in mind, we dynamically return a "this" select option item (by selectedIndex ):
![]()
Here is a JavaScript code line:
Assuming that the dropdown menu named list name=»list» and included in a form with name attribute name=»form1″ .
![]()
![]()
I think you can attach an event listener to the select tag itself e.g:
In this scenario, you should make sure you have a value attribute for all of your options, and they are not null.
![]()
![]()
You should be using querySelector to achieve this. This also standardizes the way of getting a value from form elements.
var dropDownValue = document.querySelector(‘#ddlViewBy’).value;
![]()
![]()
![]()
Here’s an easy way to do it in an onchange function:
![]()
There is a workaround, using the EasyUI framework with all of its plugins.
You only need to add some EasyUI object that can read from an input as a "bridge" to the drop-down menu.
To the left, the drop-down, to the right, the easyui-searchbox:

Mind: the var name is the ‘1’ or ‘2’, that is, the "value of the drop-down", while var value is the value that was entered in the easyui-searchbox instead and not relevant if you only want to know the value of the drop-down.
I checked how EasyUI fetches that #mm name, and I could not find out how to get that name without the help of EasyUI. The jQuery behind getName :
Mind that the return of this function is not the value of the easyui-searchbox, but the name of the #mm drop-down that was used as the menu parameter of the easyui-searchbox. Somehow EasyUI must get that other value, therefore it must be possible.
If you do not want any plugin to be seen, make it as tiny as possible? Or find perhaps a plugin that does not need a form at all in the link above, I just did not take the time.