JavaScript Select Element Demo

Элемент select в JavaScript

Краткое описание: в этом уроке вы узнаете, как работать с элементом в JavaScript.

Знакомство с элементами HTML select

Элемент предоставляет вам список вариантов. Элемент позволяет выбрать один или несколько вариантов.

Для создания элемента используются элементы и . Например:

Code language: HTML, XML (xml)

Приведенный выше элемент позволяет вам выбрать один вариант за один раз.

Чтобы включить множественный выбор, вы добавляете атрибут multiple к элементу следующим образом:

Code language: HTML, XML (xml)

Тип HTMLSelectElement .

Для взаимодействия с элементом в JavaScript используется тип HTMLSelectElement .

Тип HTMLSelectElement имеет следующие полезные свойства:

  • selectedIndex — возвращает основанный на нуле индекс выбранного варианта. selectedIndex равен -1 , если ни одна опция не выбрана. Если элемент допускает несколько вариантов выбора, selectedIndex возвращает value первого варианта.
  • value — возвращает свойство value первого выбранного элемента опции, если оно есть. В противном случае возвращается пустая строка.
  • multiple — возвращает true , если элемент допускает множественный выбор. Это эквивалентно атрибуту multiple .

Свойство selectedIndex .

Чтобы выбрать элемент , вы используете DOM API, такие как getElementById() или querySelector() .

В следующем примере показано, как получить индекс выбранного варианта:

Code language: HTML, XML (xml)
  • Сначала выберите элементы и с помощью метода querySelector() .
  • Затем прикрепите к кнопке слушатель события click и покажите выбранный индекс с помощью метода alert() , когда кнопка будет нажата.

Свойство value

Свойство value элемента зависит от элемента и его атрибута HTML multiple :

  • Если ни один вариант не выбран, свойство value поля выбора является пустой строкой.
  • Если опция выбрана и имеет атрибут value , свойство value поля выбора является значением выбранной опции.
  • Если опция выбрана и не имеет атрибута value , свойство value поля выбора является текстом выбранной опции.
  • Если выбрано несколько вариантов, свойство value поля выбора определяется из первого выбранного варианта на основе двух предыдущих правил.
Code language: HTML, XML (xml)
  • Если выбран первый вариант, свойство value поля будет пустым.
  • Если выбрать последний вариант, свойство value поля выбора будет Ember.js , поскольку выбранный вариант не имеет атрибута value .
  • Если вы выберете второй или третий вариант, свойство value будет «1» или «2» .
Читайте также:  Убрать перевод строки питон

Тип HTMLOptionElement

В JavaScript тип HTMLOptionElement представляет элемент .

Тип HTMLOptionElement имеет следующие удобные свойства:

  • index — индекс опции в коллекции опций.
  • selected — возвращает true , если опция выбрана. Вы устанавливаете это свойство в true , чтобы выбрать опцию.
  • text — возвращает текст опции.
  • value — возвращает атрибут значения HTML.

Элемент имеет свойство options , которое позволяет получить доступ к опциям коллекции:

selectBox.options
Code language: CSS (css)

Например, чтобы получить доступ к тексту и значению второго варианта, вы используете следующее:

const text = selectBox.options[1].text; const value = selectBox.options[1].value;
Code language: JavaScript (javascript)

Чтобы получить выбранный вариант элемента с одним выбором, вы используете следующий код:

let selectedOption = selectBox.options[selectBox.selectedIndex];
Code language: JavaScript (javascript)

Затем вы можете получить доступ к text и value выбранного варианта через свойства text и value :

const selectedText = selectedOption.text; const selectedValue = selectedOption.value;
Code language: JavaScript (javascript)

Когда элемент допускает несколько вариантов выбора, вы можете использовать свойство selected , чтобы определить, какие варианты выбраны:

Code language: HTML, XML (xml)

В этом примере sb.options является объектом типа массива, поэтому у него нет методов filter() , как у объекта Array .

Чтобы заимствовать эти методы у объекта Array , вы используете метод call() . Например, следующее действие возвращает массив выбранных опций:

[].filter.call(sb.options, option => option.selected)
Code language: PHP (php)

А чтобы получить свойство text опций, вы соединяете результат метода filter() с методом map() , вот так:

.map(option => option.text);
Code language: JavaScript (javascript)

Резюме

  • Элемент позволяет выбрать один или несколько вариантов. Добавьте атрибут multiple к элементу , чтобы включить множественный выбор.
  • HTMLSelectElement представляет элемент . Используйте selectedIndex и value , чтобы получить индекс и значение выбранного варианта.
  • Элемент HTMLOptionElement представляет элемент . Если опция выбрана, свойство selected равно true. Свойства selectedText и selectedValue возвращают text и value выбранной опции.

Источник

Select type Property

Return which type of form element a drop-down list is:

Description

The type property returns which type of form element a drop-down list is.

For a drop-down list this will be «select-one» or «select-multiple».

Browser Support

Syntax

Technical Details

More Examples

Example

Return which type of form element a drop-down list that allows multiple selections is:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Читайте также:  No python plugins found

Источник

JavaScript Select Option

We will understand how to manage select> option in JavaScript in this tutorial.

HTML Select Option

The option permits us to choose one option at a time which is mentioned above.

If we wish more than one selections, we can include attribute to multiple> elements below:

HTMLSelectElement type

We use the HTMLSelectElement type for interacting with option in JavaScript.

The HTMLSelectElement type contains the following helpful attributes:

JavaScript Select Option

  • selectedIndex- This attribute gives a zero-based selected options index. The selectedIndex will be -1 when no option is chosen. When the option permits more than once selections, the selectedIndex gives the first option’s value.
  • value- The value attribute gives the value attribute of the initially selected option component if there is a single, otherwise, it will return the empty strings.
  • multiple- The multiple attributes give true when the component permits more than one selection. It is the same as the multiple attributes.

selectedIndex property

The example indicates how to obtain the selected option index which is mentioned below:

How it works:

  • Initially, select the and components with the help of querySelector() method.
  • After that, link the click event listener to this button and display the selected index with the help of alert() method if the button is pressed.

value property

  • The value property of a select box will be an empty string when no option has been selected.
  • The value property of a select box will be the value of the chosen option when an option has been chosen and contains the value attribute.
  • The value property of a select box will be the text of the chosen option when an option has been chosen and contains no value attribute.
  • The value property of a select box will be derived from the initial selected option regarding the past two rules when more than one options are chosen.

Consider the below example:

  • The value attribute of the element is empty when we select the initial option.
  • The value attribute of a select box will be Ember.js due to the chosen option contains no value attribute when we choose the last option.
  • The value attribute will be “1” or “2” when we choose the third or second option.

HTMLOptionElement type

The HTMLOptionElement type illustrates the element in JavaScript.

This type contains the following properties:

JavaScript Select Option

Index- The option’s index within the group of options.

Selected- It returns a true value if the option is chosen. We set the selected property true for selecting an option.

Text- It returns the text of the option.

Читайте также:  Автоматическое изменение картинок css

Value- It returns the value attribute of HTML.

The component contains an option attribute that permits us for accessing the collection options:

For example, for accessing the value and text of the second option, we use the below:

For getting a selected option of the component along with an individual selection, we use the below code:

After that, we can access the value and text of a selected option by value and text properties:

When the component permits more than one selections, we can use a selected attribute for determining which option is selected:

In the example, the sb.option is the array-like object. Hence, it does not contain the filter() method same as the Array object.

For borrowing these types of methods through an array object, we use a call() method, the below gives the array of chosen options:

And for getting the text attribute of any option, we can chain the outcome of a filter() method along with a map() method like below:

To get Selected Option using for loop

WE can use the for loop for iterating by the selected list options for determining which is chosen. A function could be described for returning the reference to a selected option or the value. The below gives the reference to a selected option:

This function gives a single chosen option, which is compatible for the select-one type of select list. The same function compatible for select-multiple type pf select lists could give more than one selected option.

Summary

  • The component permits us for selecting one or more options. We can include the multiple property to the component for enabling more than one selections.
  • The HTMLOptionElement illustrates the component. The selected attribute is true if an option is chosen. The selected value and selected text attributes return the value Add the text of the chosen option.
  • The HTMLSelectElement illustrates the component. We can use the value and selected index for getting the value and index of the chosen option.

Источник

Javascript select one type

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Оцените статью