Home >Web Front-end >JS Tutorial >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!