Home >Web Front-end >JS Tutorial >How to Capture the Value of a Select Dropdown Before It Changes?

How to Capture the Value of a Select Dropdown Before It Changes?

DDD
DDDOriginal
2024-11-09 08:21:02912browse

How to Capture the Value of a Select Dropdown Before It Changes?

Retrieving Select Dropdown Value Before Change

To capture the value of a select dropdown before it's changed, a combination of the 'focus' and 'change' events can be used.

Firstly, create a closure and declare a 'previous' variable to store the value of the select before change.

Next, bind the 'focus' event handler to all select elements ('$("select")'). Within this handler, store the current value in the 'previous' variable on focus.

Finally, bind the 'change' event handler to the same select elements. In the change handler, after the change occurs, the 'previous' variable holds the value prior to the change. Do whatever necessary with the previous value, and then update 'previous' to the current value.

An example of this approach:

(function () {
    var previous;

    $("select").on('focus', function () {
        previous = this.value;
    }).change(function() {
        alert(previous);
        previous = this.value;
    });
})();

A working example can be found at: http://jsfiddle.net/x5PKf/766

The above is the detailed content of How to Capture the Value of a Select Dropdown Before It Changes?. 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