Javascript select get all selected

Содержание
  1. Работа с select с помощью JQuery
  2. Получить значение выбранного элемента
  3. Получить текст выбранного элемента
  4. Узнать сколько элементов option в списке select
  5. Узнать количество выбранных элементов
  6. Выбор элементов
  7. Выбрать первый элемент:
  8. Выбрать последний элемент:
  9. Выбрать элемент c value = 2:
  10. Выбрать элемент содержащий текст «виноград»:
  11. Выбрать все элементы:
  12. Снять выделение:
  13. Заблокировать и разблокировать select
  14. Добавление option в select
  15. Добавить элемент в начало select:
  16. Добавить элемент в конец select:
  17. Добавить элемент до и после option c value = 2:
  18. Добавить элемент до и после option c текстом «апельсин»:
  19. Добавление элементов в optgroup
  20. Добавить элементы option в select из массива
  21. Удаление option из select
  22. Удалить выбранный элемент:
  23. Удалить первый элемент:
  24. Удалить элемент c value = 4:
  25. Удалить элемент содержащий текст «виноград»:
  26. Очистить весь select:
  27. Комментарии 5
  28. Другие публикации
  29. Javascript select get all selected
  30. # Table of Contents
  31. # Get all selected values of a multiple Select field in JS
  32. # Get all selected values of a multiple Select field using Array.map()
  33. # Get all selected values of a multiple Select field using Array.filter()
  34. # Additional Resources
  35. Get all options of a select with JavaScript/jQuery
  36. 1. Using jQuery
  37. JS
  38. HTML
  39. JS
  40. HTML
  41. JS
  42. HTML
  43. 2. Using JavaScript
  44. JS
  45. HTML
  46. JS
  47. HTML

Работа с select с помощью JQuery

Сборник методов JQuery для работы с выпадающими списками .

Получить значение выбранного элемента

$('#select').val(); /* или */ $('select[name=fruct]').val();

Для списков с множественном выбором (multiple) метод val() вернет значения в виде массива.

Получить текст выбранного элемента

$('#select option:selected').text(); /* или */ $('#select option:selected').html();

Узнать сколько элементов option в списке select

Узнать количество выбранных элементов

$('#select option:selected').size();

Выбор элементов

Выбрать первый элемент:

$('#select option:first').prop('selected', true);

Выбрать последний элемент:

$('#select option:last').prop('selected', true);

Выбрать элемент c value = 2:

$('#select option[value=2]').prop('selected', true);

Выбрать элемент содержащий текст «виноград»:

$('#select option:contains("виноград")').prop('selected', true);

Выбрать все элементы:

$('#select option').prop('selected', true);

Снять выделение:

$('#select option').prop('selected', false);

Заблокировать и разблокировать select

// Заблокировать $('#select').prop('disabled', true); // Разблокировать $('#select').prop('disabled', false); 

Добавление option в select

Добавить элемент в начало select:

$('#select').prepend('');

Добавить элемент в конец select:

Добавить элемент до и после option c value = 2:

// До $('#select option[value=2]').before(''); // После $('#select option[value=2]').after(''); 

Добавить элемент до и после option c текстом «апельсин»:

// До $('#select option:contains("апельсин")').before(''); // После $('#select option:contains("апельсин")').after('');

Добавление элементов в optgroup

// Добавить элемент в начало группы «Фрукты» $('#select optgroup[label=Фрукты]').prepend(''); // Добавить элемент в конец группы «Фрукты» $('#select optgroup[label=Фрукты]').append('');

Добавить элементы option в select из массива

var array = ; $.each(array, function(key, value) < $('#select').append(''); >);

Удаление option из select

Удалить выбранный элемент:

$('#select option:selected').remove();

Удалить первый элемент:

Удалить элемент c value = 4:

$('#select option[value=4]').remove();

Удалить элемент содержащий текст «виноград»:

$('#select option:contains("виноград")').remove();

Очистить весь select:

$('#select').empty(); /* или */ $('#select option').remove();

Комментарии 5

Здравствуйте! Спасибо за статью, но подскажите как выбрать несколко значений select, если у меня multiple
У вас написано как выбрать с одним значением:

$('#select option[value=2]').prop('selected', true);

А как сделать если нужно выбрать со значением например 2 и 3?
Пробовал так: $(‘#select option[value=2,3]’).prop(‘selected’, true);
Но выдает ошибку.

var array = ; 

$.each(array, function(key, value) $(`#select option[value="$"]`).prop('selected', true);
>);
Выбрать элемент c value = 2:
$('#select option[value=2]').prop('selected', true);
JS
Выбрать элемент содержащий текст «виноград»:
$('#select option:contains("виноград")').prop('selected', true);

Не работают эти конструкции. Выдаются ошибки. Эти примеры по всему интернету, но у меня не получается таким образом выбрать позицию, да и сам phpstorm ругается, что г@&но какое-то ввёл.

Читайте также:  Algorithm interview questions in java

кто подскажет куда нужно прописать сумму и количество дней что рассчитать стоимость и срок
/*Калькулятор*/
function calculate() let sum = parseInt($(«#SelectSiteType option:selected»).val()) + parseInt($(«#SelectDesign option:selected»).val()) + parseInt($(«#SelectAdaptability option:selected»).val());
let days = parseInt($(«#SelectSiteType option:selected»).attr(«days»)) + parseInt($(«#SelectDesign option:selected»).attr(«days»)) + parseInt($(«#SelectAdaptability option:selected»).attr(«days»));
$(» .digit»).text(sum);
$(» .digit1″).text(days);
>;
calculate();
$(«select»).on(«change», function() calculate();
>);

Авторизуйтесь, чтобы добавить комментарий.

Другие публикации

Селекторы JQuery

В jQuery, селекторы в основном позаимствованы из CSS 1-3, также добавлены свои, что дало хороший набор инструментов для манипуляций с элементами в документе.

Источник

Javascript select get all selected

Last updated: May 20, 2023
Reading time · 4 min

banner

# Table of Contents

# Get all selected values of a multiple Select field in JS

To get all selected values of a multiple select field:

  1. Use a for. of loop to iterate over the select field’s options.
  2. Check if each option is selected.
  3. Push the values of the selected options into an array.

Here is the HTML for the example.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> h2>bobbyhadz.comh2> select multiple name="languages" id="language-select"> option value="">--Choose one or more options--option> option value="javascript">JavaScriptoption> option value="typescript">TypeScriptoption> option value="python">Pythonoption> option value="java">Javaoption> option value="php">PHPoption> select> br /> br /> button id="btn">Submitbutton> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const select = document.getElementById('language-select'); const button = document.getElementById('btn'); button.addEventListener('click', () => const selectedOptions = []; for (const option of select.options) if (option.selected) selectedOptions.push(option.value); > > console.log(selectedOptions); >);

We used the document.getElementById method to get the select and button elements.

The next step is to add a click event listener to the button element.

Each time the button is clicked, the event handler function is invoked.

We used a for. of loop to iterate over the options of the select element.

Copied!
const select = document.getElementById('language-select'); const button = document.getElementById('btn'); button.addEventListener('click', () => const selectedOptions = []; for (const option of select.options) if (option.selected) selectedOptions.push(option.value); > > console.log(selectedOptions); >);

On each iteration, we check if the current option element is selected.

If the condition is met, we push the value of the option element into the selectedOptions array.

If you haven’t set the value attribute on some of the options, you might need to use the text property as a fallback.

Copied!
selectedOptions.push(option.value || option.text);

You can also extract the logic into a reusable function.

Copied!
const select = document.getElementById('language-select'); const button = document.getElementById('btn'); button.addEventListener('click', () => const selectedOptions = getAllSelectValues(select); console.log(selectedOptions); >); function getAllSelectValues(select) const selectedOptions = []; for (const option of select.options) if (option.selected) selectedOptions.push(option.value); > > return selectedOptions; >

The getAllSelectValues() function takes a select element as a parameter and returns an array that contains the values of all of its selected options.

You could also use the Array.forEach method instead of a for. of loop.

Copied!
const select = document.getElementById('language-select'); const button = document.getElementById('btn'); button.addEventListener('click', () => const selectedOptions = []; Array.from(select.options).forEach(option => if (option.selected) selectedOptions.push(option.value); > >); console.log(selectedOptions); >);

The function we passed to the forEach() method gets called with each option element.

# Get all selected values of a multiple Select field using Array.map()

You can also use the document.querySelector method to retrieve all selected option elements and use Array.map method to get an array of the selected values.

Here is the HTML for the example.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> h2>bobbyhadz.comh2> select multiple name="languages" id="language-select"> option value="">--Choose one or more options--option> option value="javascript">JavaScriptoption> option value="typescript">TypeScriptoption> option value="python">Pythonoption> option value="java">Javaoption> option value="php">PHPoption> select> br /> br /> button id="btn">Submitbutton> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const button = document.getElementById('btn'); button.addEventListener('click', () => const selectedOptions = document.querySelectorAll( '#language-select option:checked', ); const selectedValues = Array.from(selectedOptions).map( option => option.value, ); console.log(selectedValues); >);

We used the document.querySelectorAll() method to get a collection of all the selected option elements.

Copied!
const selectedOptions = document.querySelectorAll( '#language-select option:checked', );

Alternatively, you can call the querySelectorAll() method directly on the select element.

Copied!
const select = document.getElementById('language-select'); const button = document.getElementById('btn'); button.addEventListener('click', () => // 👇️ calling querySelectorAll() on select element const selectedOptions = select.querySelectorAll('option:checked'); const selectedValues = Array.from(selectedOptions).map( option => option.value, ); console.log(selectedValues); >);

The next step is to convert the collection to an array using Array.from.

Once we have an array of the selected option elements, we use the Array.map() method to get an array of the selected values.

You can also get the selected option elements by accessing the selectedOptions property on the select element.

Copied!
const select = document.getElementById('language-select'); const button = document.getElementById('btn'); button.addEventListener('click', () => // 👇️ access selectedOptions property const selectedOptions = select.selectedOptions; const selectedValues = Array.from(selectedOptions).map( option => option.value, ); console.log(selectedValues); >);

The selectedOptions property returns a list of all of the option elements within the select element that are currently selected.

The property returns an HTMLCollection , so we used the Array.from() method to convert it to an array before calling Array.map() .

# Get all selected values of a multiple Select field using Array.filter()

You can also use the Array.filter method to get all selected values of a multiple select field.

Here is the HTML for the example.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> h2>bobbyhadz.comh2> select multiple name="languages" id="language-select"> option value="">--Choose one or more options--option> option value="javascript">JavaScriptoption> option value="typescript">TypeScriptoption> option value="python">Pythonoption> option value="java">Javaoption> option value="php">PHPoption> select> br /> br /> button id="btn">Submitbutton> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const select = document.getElementById('language-select'); const button = document.getElementById('btn'); button.addEventListener('click', () => const selectedValues = Array.from(select.options) .filter(option => option.selected) .map(option => option.value); console.log(selectedValues); >);
  1. We used the Array.from() method to convert the collection of option elements to an array.
  2. We then used the Array.filter() to get an array containing only the selected option elements.
  3. Lastly, we used Array.map() to get an array of the values of the selected option elements.

# 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.

Источник

Get all options of a select with JavaScript/jQuery

This post will discuss how to get all options of a select in JavaScript and jQuery.

1. Using jQuery

With jQuery, you can use the .each() method, which is a concise and less error-prone way to iterate over the DOM elements.

JS

HTML

To filter the selected options, you can use the :selected property.

JS

HTML

A better alternative is to use the jQuery.map() instead.

JS

HTML

2. Using JavaScript

In pure JavaScript, you can loop through each using for-of statement:

JS

HTML

Alternatively, you can use the Array.prototype.map() method:

JS

var values = Array . from ( document . getElementById ( «pets» ) . options ) . map ( e = > e . value ) ;

HTML

That’s all about getting all options of a select in JavaScript and jQuery.

Average rating 4.64 /5. Vote count: 28

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Tell us how we can improve this post?

Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding 🙂

This website uses cookies. By using this site, you agree to the use of cookies, our policies, copyright terms and other conditions. Read our Privacy Policy. Got it

Источник

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