Home >Common Problem >How to bind select change event in jquery

How to bind select change event in jquery

尊渡假赌尊渡假赌尊渡假赌
尊渡假赌尊渡假赌尊渡假赌Original
2023-06-09 16:02:073372browse

Jquery binding select change event method: 1. Create a jQuery sample file; 2. Use the "$('select')" selector to select all select elements, and then bind with the "on()" method change event; 3. After the event occurs, the callback function uses the ".val()" and ".find(':selected')" methods to obtain the value and text of the selected item; 4. The console outputs the selected content, or Just display it on the page.

How to bind select change event in jquery

Operating system for this tutorial: Windows 10 system, jQuery3.6.0 version, Dell G3 computer.

Using jQuery, you can simply bind the change event to listen for changes in the select element.

Use the following code to implement:

$(document).ready(function() {
  // 选择 select 元素,并绑定 change 事件
  $('select').on('change', function() {
    // 获取选中项的值和文本
    var selectedValue = $(this).val();
    var selectedText = $(this).find(':selected').text();
    
    // 在控制台输出选中项的值和文本
    console.log('选中了:' + selectedValue + ',' + selectedText);
    
    // 如果需要在页面上显示选中项的值或文本,可以使用以下代码
    // $('#result').text(selectedValue); 
    // $('#result').text(selectedText);
  });
});

The $('select') selector in the above code is used to select all select elements, and then the on() method binds the change event to above them. The callback function will be triggered when the user selects an option in the select element.

The callback function first obtains the value and text of the selected item, here the .val() and .find(':selected') methods are used. The selected content can then be output to the console or displayed on the page (by modifying the .text() of the corresponding element).

If you want to operate on a specific select element in the page, select based on a selector such as its ID or class name. For example: $('#my-select') or $('.my-select').

The above is the detailed content of How to bind select change event in jquery. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn