how to compare previous value with current in jquery
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:
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:
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.