Home > Web Front-end > JS Tutorial > How to Preserve Select Dropdown Value Before Change with jQuery?

How to Preserve Select Dropdown Value Before Change with jQuery?

Mary-Kate Olsen
Release: 2024-11-17 13:32:02
Original
584 people have browsed it

How to Preserve Select Dropdown Value Before Change with jQuery?

Preserving Select Dropdown Value Before Change with jQuery

Achieving this is possible by combining the focus and change events in jQuery. Here's how you can do it:

($ => {
  var previous;

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

In this code, we use the focus event to store the current value of the dropdown. When the dropdown is changed (change event), we can access and display the previous value before the change.

To apply this functionality to multiple select boxes on the same page, including those added after the page load via AJAX, you can use the following updated code:

$(document).ready(function() {
  $(document).on("focus", "select", function () {
    $(this).data('previous', this.value); 
  }); 

  $(document).on("change", "select", function() {
    const previous = $(this).data('previous'); 
    if (previous) {
      alert(previous); 
      $(this).data('previous', this.value); 
    }
  });
});
Copy after login

The above is the detailed content of How to Preserve Select Dropdown Value Before Change with jQuery?. For more information, please follow other related articles on the PHP Chinese website!

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