Skip to content
the poor coder

how to compare previous value with current in jquery

Poor Man
Published
Reading time
1 min read
On this page

How to Compare Previous Value with Current in jQuery#

If you want to compare the previous value with the current value in jQuery, you can use the .data() method to store the previous value in a data attribute and then compare it with the current value.

Using the .data() Method#

Here's an example:

Text

var previousValue = $('#inputField').data('previousValue');
var currentValue = $('#inputField').val();

if(previousValue != currentValue) {
  // Do something here
}

$('#inputField').data('previousValue', currentValue);

In this code, we first get the previous value from the 'previousValue' data attribute using the .data() method. We then get the current value of the input field using the .val() method. We compare the two values using the not equal to (!=) operator and if they are not equal, we do something. Finally, we store the current value in the 'previousValue' data attribute using the .data() method.

Using Global Variable#

Another way to compare previous and current values is to use a global variable to store the previous value:

Text

var previousValue;

$('#inputField').on('change', function() {
  var currentValue = $(this).val();
  
  if(previousValue != currentValue) {
    // Do something here
  }
  
  previousValue = currentValue;
});

In this code, we declare a global variable called previousValue. We then attach a change event handler to the input field using the .on() method. Inside the event handler, we get the current value of the input field using the .val() method. We compare the previous value with the current value using the not equal to (!=) operator and if they are not equal, we do something. Finally, we update the previousValue variable with the current value.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC