Html select javascript this value

и | 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].

Источник

Читайте также:  Failed to decode downloaded font css

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:

English    

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.

     function update() < var select = document.getElementById('language'); var option = select.options[select.selectedIndex]; document.getElementById('value').value = option.value; document.getElementById('text').value = option.text; >update();   

Источник

Html select javascript this value

Last updated: Jan 12, 2023
Reading time · 3 min

banner

# Get the Value/Text of Select or Dropdown on Change

To get the value and text of a select element on change:

  1. Add a change event listener to the select element.
  2. Use the value property to get the value of the element, e.g. select.value .
  3. Use the text property to get the text of the element, e.g. select.options[select.selectedIndex].text .

Here is the HTML for the examples.

Copied!
DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> select id="select" style="font-size: 3rem"> option value="">--Choose an option--option> option value="horse">Horse 🐴option> option value="wolf">Wolf 🐺option> option value="fox">Fox 🦊option> select> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const select = document.getElementById('select'); select.addEventListener('change', function handleChange(event) console.log(event.target.value); // 👉️ get selected VALUE // 👇️ get selected VALUE even outside event handler console.log(select.options[select.selectedIndex].value); // 👇️ get selected TEXT in or outside event handler console.log(select.options[select.selectedIndex].text); >);

We added a change event listener to the select element.

We used the target property on the event object. The target property is a reference to the object (element) on which the event was dispatched.

In the example, the event.target property points to the select element, because that is the element on which the event was dispatched.

# Read or set the value of a select element

The value property allows us to read or set the value of the select element.

Copied!
const select = document.getElementById('select'); // ✅ Read value console.log(select.value); // 👉️ "" // ✅ Set value select.value = 'fox'; console.log(select.value); // 👉️ "fox"

When setting the value of a select element, make sure to set it to one of the values of the option elements.

The options property on the select element returns an array-like object that contains all of the options of the select element.

Copied!
const select = document.getElementById('select'); console.log(select.options); // 👉️ [option, option, option, option] select.addEventListener('change', function handleChange(event) console.log(select.options); // 👉️ [option, option, option, option] >);

# Get the index of the currently selected option element

We can use the selectedIndex property to get the index of the currently selected option .

Copied!
const select = document.getElementById('select'); console.log(select.selectedIndex); select.addEventListener('change', function handleChange(event) console.log(select.selectedIndex); >);

Initially it is set to 0 , but if you console.log the selectedIndex in the handleChange function and change the selected element, you will see the index change.

# Get the text and value of the selected option using the index

The selectedIndex property can be used to get the index of the currently selected option element. The index can be used to get the element’s value and text .

Copied!
const select = document.getElementById('select'); select.addEventListener('change', function handleChange(event) // 👇️ get selected VALUE even outside event handler console.log(select.options[select.selectedIndex].value); // 👇️ get selected TEXT in or outside event handler console.log(select.options[select.selectedIndex].text); >);

This approach can be used both inside and outside of an event handler function.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

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); 

Источник

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