Home > Web Front-end > JS Tutorial > body text

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

Susan Sarandon
Release: 2024-11-13 09:44:02
Original
686 people have browsed it

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

Retrieving Select Dropdown Value Before Change

In web development, it's often necessary to capture the value of a select dropdown before it changes. However, the typical 'change' event handler retrieves the value after the change occurs.

Consider the following HTML snippet:

<select name="test">
  <option value="stack">Stack</option>
  <option value="overflow">Overflow</option>
  <option value="my">My</option>
  <option value="question">Question</option>
</select>
Copy after login

If the "My" option is currently selected, and the user changes it to "Stack," the value returned by the 'change' event handler will be "Stack."

To retrieve the previous value before the change, a clever solution can be employed using a combination of the 'focus' and 'change' events:

(function () {
  var previous;

  $("select").on('focus', function () {
    // Store the current value on focus and on change
    previous = this.value;
  }).change(function() {
    // Do something with the previous value after the change
    alert(previous);

    // Make sure the previous value is updated
    previous = this.value;
  });
})();
Copy after login

When the user focuses on the dropdown, the 'focus' event fires and stores the current value in the 'previous' variable. Subsequently, when the user changes the selection, the 'change' event fires and alerts the previous value stored in 'previous.'

This approach ensures that the value before the change is readily available for processing, providing greater flexibility in handling select dropdown changes effectively.

The above is the detailed content of How to Get the Previous Value of a Select Dropdown Before It Changes?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template