Html select получить выбранное значение

Содержание
  1. Html select получить выбранное значение
  2. Скрипт получения значения из select jquery.
  3. Пример получения значения из select jquery.
  4. Получить текст выбранного поля select jquery
  5. Работа с select с помощью JQuery
  6. Получить значение выбранного элемента
  7. Получить текст выбранного элемента
  8. Узнать сколько элементов option в списке select
  9. Узнать количество выбранных элементов
  10. Выбор элементов
  11. Выбрать первый элемент:
  12. Выбрать последний элемент:
  13. Выбрать элемент c value = 2:
  14. Выбрать элемент содержащий текст «виноград»:
  15. Выбрать все элементы:
  16. Снять выделение:
  17. Заблокировать и разблокировать select
  18. Добавление option в select
  19. Добавить элемент в начало select:
  20. Добавить элемент в конец select:
  21. Добавить элемент до и после option c value = 2:
  22. Добавить элемент до и после option c текстом «апельсин»:
  23. Добавление элементов в optgroup
  24. Добавить элементы option в select из массива
  25. Удаление option из select
  26. Удалить выбранный элемент:
  27. Удалить первый элемент:
  28. Удалить элемент c value = 4:
  29. Удалить элемент содержащий текст «виноград»:
  30. Очистить весь select:
  31. Комментарии 5
  32. Другие публикации
  33. JavaScript: How to Get the Value of a Select or Dropdown List
  34. How to get the value of a select
  35. Getting the value of a select with jQuery
  36. How to get the text of a select
  37. Getting the text from a select with jQuery
  38. Complete example
  39. Manipulation of HTML Select Element with Javascript
  40. Important Properties and Methods of Select Element
  41. Important Properties of Option Element
  42. Setting Value of Select Element
  43. Getting the Value and Text/Label of the Selected Options
  44. Adding an Option
  45. Deleting an Option
  46. и | JavaScript
  47. HTMLSelectElement.type : получить тип
  48. HTMLSelectElement.multiple : получить и изменить тип
  49. HTMLSelectElement.length : получить и изменить количество пунктов
  50. HTMLSelectElement.add() : добавить новый пункт

Html select получить выбранное значение

Для того, чтобы получить значение из тега select с помощью jquery, вам понадобится:

Читайте также:  Технология создания html документа

Внутрь тега select помещаем тег id, чтобы мы могли обратиться к данному тегу.

Между тегами помещаем тег option.

У вас должно получиться что-то типа:

Вам потребуется кнопка button, чтобы процесс получения значения из тега «select» с jquery происходил прямо сейчас — в тот момент, когда вы нажмете кнопку.

Аналогично добавляем в кнопку id, чтобы отследить нажатие на неё.

И третий элемент — пусть это будет span, в который передадим полученное значение «select jquery«

Далее. вам нужно разобраться с кодом «jquery», который сможет получить, а потом и отправить данные в span? чтобы вы могли их увидеть.

Первое, естественно, вам нужно подключить jquery;

При нажатии на кнопку, вам потребуется click + функция:

Передаем полученное значение селекта в span с помощью метода text

Теперь весь код можем собрать.

Скрипт получения значения из select jquery.

Если интересно. Немного добавил стилей — это, конечно, не особенно относится к нашей теме «получения значения из select jquery«, но тем не менее.

Пример получения значения из select jquery.

И последний шаг в данном пункте — показать рабочий пример «получения значения из select jquery«.
Весь код расположим прямо здесь: Для получения значения из select в jquery — нажмите кнопку «Получить значение select«.

Получить значение select Нажмите кнопку!

Получить текст выбранного поля select jquery

Для получения текста выбранного поля в select jquery, вам потребуется. выше приведенный пункт . и требуется изменить лишь одну строчку кода:

Берем вот эту строчку кода:

Меняем на(ко всем «id» добавляем «_1»):

Источник

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

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

Источник

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

Источник

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