Html select option script

JavaScript select Element

Summary: in this tutorial, you will learn how to handle the element in JavaScript.

Introduction to the HTML select elements

A element provides you with a list of options. A element allows you to select one or multiple options.

To create a element, you use the and elements. For example:

select id="framework"> option value="1">Angular option> option value="2">React option> option value="3">Vue.js option> option value="4">Ember.js option> select>Code language: HTML, XML (xml)

The above element allows you to select a single option at a time.

To enable multiple selections, you add multiple attribute to element as follows:

select id="framework" multiple> option value="1">Angular option> option value="2">React option> option value="3">Vue.js option> option value="4">Ember.js option> select>Code language: HTML, XML (xml)

The HTMLSelectElement type

To interact with element in JavaScript, you use the HTMLSelectElement type.

The HTMLSelectElement type has the following useful properties:

  • selectedIndex – returns the zero-based index of the selected option. The selectedIndex is -1 if no option is selected. If the element allows multiple selections, the selectedIndex returns the value of the first option.
  • value – returns the value property of the first selected option element if there is one. Otherwise, it returns an empty string.
  • multiple – returns true if the element allows multiple selections. It is equivalent to the multiple attribute.
Читайте также:  Php показывает только код

The selectedIndex property

To select a element, you use the DOM API like getElementById() or querySelector() .

The following example illustrates how to get the index of the selected option:

html> html> head> title>JavaScript Select Element Demo title> link href="css/selectbox.css" rel="stylesheet"> head> body> form> label for="framework">Select a JS Framework label> select id="framework"> option value="1">Angular option> option value="2">React option> option value="3">Vue.js option> option value="4">Ember.js option> select> button id="btn">Get the Selected Index button> form> script> const btn = document.querySelector('#btn'); const sb = document.querySelector('#framework') btn.onclick = (event) => < event.preventDefault(); // show the selected index alert(sb.selectedIndex); >; script> body> html>Code language: HTML, XML (xml)
  • First, select the and elements using the querySelector() method.
  • Then, attach a click event listener to the button and show the selected index using the alert() method when the button is clicked.

The value property

The value property of the element depends on the element and its HTML multiple attribute:

  • If no option is selected, the value property of the select box is an empty string.
  • If an option is selected and has a value attribute, the value property of the select box is the value of the selected option.
  • If an option is selected and has no value attribute, the value property of the select box is the text of the selected option.
  • If multiple options are selected, the value property of the select box is derived from the first selected option based on the previous two rules.

See the following example:

html> html> head> title>JavaScript Selected Value title> link href="css/selectbox.css" rel="stylesheet"> head> body> div id="container"> form> label for="framework">Select a JS Framework: label> select id="framework"> option value="">Angular option> option value="1">React option> option value="2">Vue.js option> option>Ember.js option> select> button id="btn">Get the Selected Value button> form> div> script> const btn = document.querySelector('#btn'); const sb = document.querySelector('#framework') btn.onclick = (event) => < event.preventDefault(); alert(sb.value); >; script> body> html>Code language: HTML, XML (xml)
  • If you select the first option, the value property of the is empty.
  • If you select the last option, the value property of the select box is Ember.js because the selected option has no value attribute.
  • If you select the second or third option, the value property will be «1» or «2» .

The HTMLOptionElement type

In JavaScript, the HTMLOptionElement type represents the element.

The HTMLOptionElement type has the following handy properties:

  • index – the index of the option inside the collection of options.
  • selected – returns true when the option is selected. You set this property to true to select an option.
  • text – returns the option’s text.
  • value – returns the HTML value attribute.

The element has the options property that allows you to access the collection options:

selectBox.optionsCode language: CSS (css)

For example, to access the text and value of the second option, you use the following:

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

To get the selected option of a element with a single selection, you use the following code:

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

Then you can access the text and value of the selected option via text and value properties:

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

When a element allows multiple selections, you can use the selected property to determine which options are selected:

html> html> head> title>JavaScript Select Box title> link rel="stylesheet" href="css/selectbox.css"> head> body> div id="container"> form> label for="framework">Select one or more JS Frameworks: label> select id="framework" multiple> option value="1">Angular option> option value="2">React option> option value="3">Vue.js option> option value="4">Ember.js option> select> button id="btn">Get Selected Frameworks button> form> div> script> const btn = document.querySelector('#btn'); const sb = document.querySelector('#framework'); btn.onclick = (e) => < e.preventDefault(); const selectedValues = [].filter .call(sb.options, option => option.selected) .map(option => option.text); alert(selectedValues); >; script> body> html>Code language: HTML, XML (xml)

In this example, the sb.options is an array-like object, so it doesn’t have the filter() methods like an Array object.

To borrow these methods from the Array object, you use the call() method. For example, the following returns an array of selected options:

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

And to get the text property of the options, you chain the result of the filter() method with the map() method, like this:

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

Summary

  • The element allows you to select one or multiple options. Add the multiple attribute to the element to enable multiple selections.
  • The HTMLSelectElement represents the element. Use the selectedIndex and value to get the index and value of the selected option.
  • The HTMLOptionElement represents the element. If the option is selected, the selected property is true. The selectedText and selectedValue properties return the text and value of the selected option.

Источник

Manipulation of HTML Select Element with Javascript

Manipulation of the element with Javascript is quite commonly required in web applications. This tutorial explains how you can perform common operations on select element with vanilla Javascript — adding/deleting options or getting/setting the selected options.

Important Properties and Methods of Select Element

  • value : It gives the value of the first selected option (a multi-valued select may have multiple selected options)
  • options : It gives the list of all option elements in the select
  • selectedOptions : It gives the list of option elements that are currently selected
  • selectedIndex : It is an integer that gives the index of first selected option. In case no option is selected, it gives -1
  • add() : This method adds a new option to the list of options
  • remove() : This method removes an option from the select element

Important Properties of Option Element

  • value : It gives the value of the option
  • text : It gives the text inside the option
  • selected : It tells whether the option is selected or not

Setting Value of Select Element

For a single valued select, setting its value can be done with the value or the selectedIndex property.

// Set option with value 'Orange' as selected document.querySelector('#choose-fruit').value = 'Orange'; // Set the option with index 2 as selected => Sets the 'Banana' option as selected document.querySelector('#choose-fruit').selectedIndex = 2; 

For a multiple valued select, setting multiple selected options can be done by setting the selected attribute of the required option.

  
// choose the first option document.querySelector('#choose-fruit-multiple').options[0].selected = true; // also choose the third option document.querySelector('#choose-fruit-multiple').options[2].selected = true; 

This will obviously work for single valued select also, but using the value property is much direct for them.

Getting the Value and Text/Label of the Selected Options

The selectedOptions property of the select element gives the list of options that are currently selected. Each element in this list is a DOM element — so you can use the value and text property to get the value and inside text of the option.

// For a normal select (and not multi-select) the list would contain only a single element var text = document.querySelector('#choose-fruit').selectedOptions[0].text; var value = document.querySelector('#choose-fruit').selectedOptions[0].value; 

For a multiple select element, you can loop over the list to get all selected options.

  
var selected_options = document.querySelector('#choose-fruit-multiple').selectedOptions; for(var i=0; i // output Orange 2 Grapes 5 

Adding an Option

The add method can be used to add a new option in the select. You can also specify the exact positon where the option needs to be inserted.

var option = document.createElement('option'); option.text = 'BMW'; // append option at the end // new options will be Volvo, Audi, Mercedes & BMW document.querySelector('#choose-car').add(option, null); 
var option = document.createElement('option'); option.text = 'BMW'; // append option before index 0 // new options will be BMW, Volvo, Audi & Mercedes document.querySelector('#choose-car').add(option, 0); 
var option = document.createElement('option'); option.text = 'BMW'; // append option before index 2 // new options will be Volvo, Audi, BMW & Mercedes document.querySelector('#choose-car').add(option, 2); 

Deleting an Option

The remove method can be used to delete an option at a specified index.

// remove the option at index 1 // new options will be Volvo & Mercedes document.querySelector('#choose-car').remove(1); 

Источник

и | JavaScript

В Mozilla Firefox и в IE не срабатывает клик, если щёлкать по уже выбранному пункту, и весь подсчёт сбивается.

   

Тип тега

HTMLSelectElement.type : получить тип

Возвращает select-one или select-multiple , если есть атрибут multiple .

 

HTMLSelectElement.multiple : получить и изменить тип

Возвращает false или true , если есть атрибут multiple .

 

Количество пунктов

HTMLSelectElement.length : получить и изменить количество пунктов

 

HTMLSelectElement.add() : добавить новый пункт

Получить значение

select.value : выводится значение атрибута value или при его отсутствии текст выбранного тега option [whatwg.org].

Источник

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