Jquery как изменить значение select

Description: Bind an event handler to the "change" JavaScript event, or trigger that event on an element.

.change( handler )Returns: jQuery

Description: Bind an event handler to the «change» JavaScript event, or trigger that event on an element.

  • version added: 1.0.change( handler )

    • handler

      A function to execute each time the event is triggered.

  • version added: 1.4.3.change( [eventData ], handler )

    • eventData

      An object containing data that will be passed to the event handler.

    • handler

      A function to execute each time the event is triggered.

  • version added: 1.0.change()

    • This signature does not accept any arguments.

This method is a shortcut for .on( "change", handler ) in the first two variations, and .trigger( "change" ) in the third.

The change event is sent to an element when its value changes. This event is limited to <input> elements, <textarea> boxes and <select> elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.

For example, consider the HTML:

1

2

3

4

5

6

7

8

9

10

<input class="target" type="text" value="Field 1">

<option value="option1" selected="selected">Option 1</option>

<option value="option2">Option 2</option>

The event handler can be bound to the text input and the select box:

1

2

3

$( ".target" ).change(function() {

alert( "Handler for .change() called." );

Now when the second option is selected from the dropdown, the alert is displayed. It is also displayed if you change the text in the field and then click away. If the field loses focus without the contents having changed, though, the event is not triggered. To trigger the event manually, apply .change() without arguments:

1

2

3

$( "#other" ).click(function() {

After this code executes, clicks on Trigger the handler will also alert the message. The message will display twice, because the handler has been bound to the change event on both of the form elements.

As of jQuery 1.4, the change event bubbles in Internet Explorer, behaving consistently with the event in other modern browsers.

Note: Changing the value of an input element using JavaScript, using .val() for example, won’t fire the event.

Additional Notes:

  • As the .change() method is just a shorthand for .on( "change", handler ), detaching is possible using .off( "change" ).

Examples:

Attaches a change event to the select that gets the text for each selected option and writes them in the div. It then triggers the event for the initial text draw.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

<title>change demo</title>

<script src="https://code.jquery.com/jquery-3.6.3.js"></script>

<select name="sweets" multiple="multiple">

<option>Chocolate</option>

<option selected="selected">Candy</option>

<option selected="selected">Caramel</option>

$( "select option:selected" ).each(function() {

str += $( this ).text() + " ";

Demo:

To add a validity test to all text input elements:

1

2

3

$( "input[type='text']" ).change(function() {

// Check input( $( this ).val() ) for validity here

If you have a select element and want to set the selected value of a drop-down via its text description, you can achieve it using different jQuery methods. Let’s discuss them separately and choose the best one for you.

The jQuery prop() method can help you get the text value of the selected option for jQuery 1.6+ versions:

<!DOCTYPE html>
<html>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
  <body>
    <select>
      <option value="0">Value1</option>
      <option value="1">Value2</option>
    </select>
    <script>
      let text = 'Value2';
      $("select option").filter(function() {
          //may want to use $.trim in here
          return $(this).text() == text;
        }).prop('selected', true);
    </script>
  </body>
</html>

This method sets the attributes and values of the selected elements. Use it for jQuery versions below 1.6 and greater than or equal to 1.4:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
  </head>
  <body>
    <select>
      <option value="0">Value1</option>
      <option value="1">Value2</option>
    </select>
    <script>
      let text = 'Value2';
      $("select option").filter(function() {
          //may want to use $.trim in here
          return $(this).text() == text;
        }).attr('selected', true);
    </script>
  </body>
</html>

This approach will work in versions above 1.6 but less than 1.9. In jQuery 1.9+ versions it won’t work. For 1.9+ versions use prop() instead of attr().

The val() method also sets the option that corresponds to the passed value:

<!DOCTYPE html>
<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
  </head>
  <body>
    <select>
      <option value="0">Value1</option>
      <option value="1">Value2</option>
    </select>
    <script>
      let text = 'Value2';
      $("select option").filter(function() {
          //may want to use $.trim in here
          return $(this).text() == text;
        }).attr('selected', true);
    </script>
  </body>
</html>

The .prop() method is used to retrieve the property value for the first element only in the matched set. If the value of a property has not been set or the matched set has no elements, it will return undefined. Use jQuery’s .each() or .map() looping methods to get the value for each element individually.

The .attr() method is used to get the attribute value for the first element only in the matched set. Use the .each() or .map() looping methods for getting the value for each element individually. The .attr() method returns undefined for those attributes that have not been set for jQuery 1.6 version. Use the .prop() method for retrieving and changing DOM properties such as the checked, selected, or disabled state of form elements.

The .val() method is mainly used to get the values of form elements such as input, select and textarea. It will return undefined if it is called on an empty set. When the first element in the set is a select-multiple, val() returns an array that contains the value of each selected option. If no option is selected, it will return an empty array for jQuery 3.0 version. For versions below jQuery 3.0, it returns null.

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

1

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

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

JS

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

2

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

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

JS

3

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

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

JS

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

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

JS

4

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

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

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

JS

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

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

JS

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

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

JS

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

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

JS

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

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

JS

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

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

JS

5

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

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

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

JS

6

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

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

$('#select').prepend('<option value="">новый option</option>');

JS

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

$('#select').append('<option value="">новый option</option>');

JS

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

// До
$('#select option[value=2]').before('<option value="">новый option</option>');

// После
$('#select option[value=2]').after('<option value="">новый option</option>');

JS

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

// До
$('#select option:contains("апельсин")').before('<option value="">новый option</option>');

// После
$('#select option:contains("апельсин")').after('<option value="">новый option</option>');

JS

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

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

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

JS

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

var array = {1: 'яблоко', 2: 'апельсин', 3: 'виноград'};

$.each(array, function(key, value) {
	$('#select').append('<option value="' + key + '">' + value + '</option>');
});

JS

7

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

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

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

JS

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

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

JS

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

JS

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

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

JS

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

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

JS

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

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

JS

05.11.2017, обновлено 15.09.2022

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

Селекторы JQuery

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

Селект с чекбоксами

Селект с множественным выбором (select multiple) весьма не удобен, при выборе часто забываешь нажимать сtrl и все сбрасывается. В место него можно использовать чекбоксы в выпадающем списке.

Работа с массивами PHP – создание, наполнение, удаление

Основные примеры работы с массивами PHP. Создание, наполнение, извлечение удаление значений.

Работа с Input Text jQuery

Сборник приемов JQuery для работы с текстовыми полями. Во всех примерах используется следующий html код…

Работа с Textarea jQuery

Сборник jQuery приемов с textarea — получить содержимое, вставить значение, подсчет количества символов и строк и т.д.

Пример парсинга html-страницы на phpQuery

phpQuery – это удобный HTML парсер взявший за основу селекторы, фильтры и методы jQuery, которые позволяют…

Jquery работа с selectОчень часто приходится сталкиваться с раскрывающимся списком <select>, поэтому набралась небольшая коллекция советов. Элементы <select> обычно имеют два значения, к которым нужно обратиться. Это значение атрибута value соответствующего элемента option и его текстовое значение. Для примера возьмем следующий код:

<select id="town">
  <option value="Moscow">Москва</option>
  <option value="St. Petersburg">Санкт-Петербург</option>
  <option value="Sochi">Сочи</option>
  <option value="Novosibirsk" selected>Новосибирск</option>
  <option value="Kazan">Казань</option>
</select>
  1. Получим значение value, выбранной опции:
    $("#town").val(); // Novosibirsk
  2. Получим текст выбранной опции:
    $("#town option:selected").text(); // Новосибирск
  3. Сделать <select> недоступным:
    $("#town").attr("disabled", "disabled");
  4. Разблокировать <select>
    $("#town").attr("disabled","");
  5. Удалить выбранный элемент:
    $("#town :selected").remove(); // будет удален Новосибирск
  6. Удалить первый элемент:
    $("#town :first").remove(); // будет удалена Москва
  7. Удалить последний элемент:
    $("#town :last").remove(); // будет удалена Казань
  8. Удалить элемент, у которого value=’Sochi’:
    $("#town option[value='Sochi']").remove();
    $("#town [value='Sochi']").remove(); // сокращенно
  9. Очистить весь список <select>
    $("#town").empty();
  10. Перебрать все элементы списка <select> и вывести в блок с id=«result»:
    var result = "";
    $('#town option').each(function(){
      result = result + this.text + "<br/>";
    });
    $('div#result').html(result);
  11. Сделать выбранным последний элемент:
    $("#town :last").attr("selected", "selected"); // будет выбрана Казань
  12. Сделать выбранным второй элемент:
    $("#town :nth-child(2)").attr("selected", "selected"); // будет выбран Санкт-Петербург
  13. Сделать выбранным элемент, содержащий текст ‘Новосибирск’:
    // Первый вариант
    $("#town :contains('Новосибирск')").attr("selected", "selected");               
    
    // Второй вариант
    $("#town").find("option:contains('Новосибирск')").attr("selected", "selected");
    
    // Третий вариант (не зависит от регистра)
    var opt = $('option');
    opt.each(function(indx, element){
      if ( $(this).text().toLowerCase() == 'Новосибирск'.toLowerCase() ) {$(this).attr("selected", "selected");}
    });

    В первом и втором вариантах используем селектор по тексту :contains(text), который чувствителен к регистру. Третий вариант от регистра не зависит.

  14. Сделать выбранным элемент, value которого = St. Petersburg:
    $("#town option[value='St. Petersburg']").attr("selected", "selected");
  15. Добавить элемент в начало списка <select>:
    $("#town").prepend('<option value="Ryazan">Рязань</option>');
  16. Добавить элемент в конец списка <select>:
    $("#twon").append('<option value="Samara">Самара</option>');
  17. Добавить новый элемент после третьего:
    $("#town option:nth-child(3)").after('<option value="Voronezh">Воронеж</option>');
    
  18. Добавить несколько элементов option в список <select> из массива:
    var newOptions = {
    "Ryaza": "Рязань",
    "Samara": "Самара"
    };
    
    $.each(newOptions, function(key, value) {
      $('#town').append($("", {
        value: key,
        text: value
      }));
    });
  19. Количество элементов option в списке <select>:
    $("select[id=town] option").size();
  20. Проверяем, выбран ли элемент в списке <select>:
    if ( $("#town").val() ) {...}
  21. Сделать все элементы в списке <select> не выбранными:
    $('#town option:selected').each(function(){
      this.selected=false;
    });

Если у вас есть еще предложения или вопросы, пишите в комментариях!


Элемент select позволят осуществлять пользавателю выбор из списка необходимую опцию или несколько опций в случае множественного выбора. Довольно часто необходимо управлять элементом select в динамике. Здесь я привожу некоторые шпаргалки по управлению элементом с помощью библиотеки jQuery

Для начала создадим html элемент select с набором опций option с тестовыми значениями.

HTML

<select id="tema" style="width: 70px;">
    <option value="html">HTML</option>
    <option value="php">PHP</option>
    <option value="js">JS</option>
    <option value="jquery" selected>jQuery</option>
    <option value="css">CSS</option>
</select>

Получаем значение value, выбранной опции элемента select:

JS

$('#tema').val(); // jquery

Получаем текст, выбранной опции элемента select:

JS

$('#tema option:selected').text(); // jQuery

Делаем элемент select недоступным и наоборот.

JS

//Удаление выбранной опции option элемента select
$("#tema :selected").remove();

//Удаление первой опции option элемента select
$("#tema :first").remove();

//Удаление последний option элемента select
$("#tema :last").remove();

//Удаление option у которого value='html' из списка элемента select
$("#tema option[value='html']").remove();
$("#tema [value='html']").remove(); // сокращенно

//Удаление всех option элемента select
$("#tema").empty();

Удаление опции option из элемента select.

JS

//Удаление выбранной опции option элемента select
$("#tema :selected").remove();

//Удаление первой опции option элемента select
$("#tema :first").remove();

//Удаление последний option элемента select
$("#tema :last").remove();

//Удаление option у которого value='html' из списка элемента select
$("#tema option[value='html']").remove();
$("#tema [value='html']").remove(); // сокращенно

//Удаление всех option элемента select
$("#tema").empty();

Перебрать и вывести все option из списка select в блок с id=»result»:

JS

var result = "";
$('#tema option').each(function(){
  result = result + this.text + "<br/>";
});
$('div#result').html(result);

 Выбрать option из списка select

В коде ниже показано как выбрать последний, второй option в списке select, и как выбрать option в select по находящимуся в нём тексте (варианты с учётом регистра и нет).

JS

//Выбрать последний option в списке select
$("#tema :last").attr("selected", "selected");

//Выбрать второй option в списке select
$("#town :nth-child(2)").attr("selected", "selected");

//Выбрать опцию содержащую текст 'PHP'

//Первый вариант
$("#tema :contains('PHP')").attr("selected", "selected");               
 
// Второй вариант
$("#tema").find("option:contains('PHP')").attr("selected", "selected");
 
// Третий вариант (не зависит от регистра)
var opt = $('#tema option');
opt.each(function(indx, element){
  if ( $(this).text().toLowerCase() == 'PHP'.toLowerCase() ) {$(this).attr("selected", "selected");}
});

Выбрать option из списка select по значению value

JS

$("#tema option[value='CSS']").attr("selected", "selected");

Добавление опций option в список select

JS

//Добавить элемент в начало списка <select>:
$("#tema").prepend( $('<option value="mysql">MySql</option>') );

//Добавить элемент в конец списка <select>:
$("#tema").append( $('<option value="mysql">MySql</option>'));
 
//Добавить новый элемент после третьего:
$("#tema option:nth-child(3)").after( $('<option value="mysql">MySql</option>') );

Добавление нескольких  опций option в список select из массива

JS

var newOptions = {
"Ryaza": "Рязань",
"Samara": "Самара"
};
 
$.each(newOptions, function(key, value) {
  $('#town').append($("", {
    value: key,
    text: value
  }));
});

Узнать количиство option в список select

JS

$("select[id=town] option").size();

Проверка — выбран ли option в список select

JS

if ( $("#town").val() ) {
   //Ваш код
   }

Отмена выбора всех option в список select

JS

$('#town option:selected').each(function(){
  this.selected=false;
});

Дата публикации: 2018-11-15 22:48:15


ТОП 10 случайных публикаций

Понравилась статья? Поделить с друзьями:
  • Jquery как изменить value input
  • Jquery как изменить src картинки
  • Jquery как изменить css свойства
  • Jquery вывод ошибки
  • Jquery validation error class