Javascript select multiple options 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 Element
  30. Introduction to the HTML select elements
  31. The HTMLSelectElement type
  32. The selectedIndex property
  33. The value property
  34. The HTMLOptionElement type
  35. Summary

Работа с 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 ругается, что г@&но какое-то ввёл.

Читайте также:  Cool HTML Parser

кто подскажет куда нужно прописать сумму и количество дней что рассчитать стоимость и срок
/*Калькулятор*/
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 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.

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.

Источник

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