Reputation: 4330
I have text boxes with .numeric class. I want check value had change or not after the edit that value.
I found this code after google.
var previousValue = $("#elm").val();
$("#elm").keyup(function(e) {
var currentValue = $(this).val();
if(currentValue != previousValue) {
previousValue = currentValue;
alert("Value changed!");
}
});
But this code will work for only one text field (with id #elm
). What should I do if I want to make it work for multiple fields (sharing the class numeric
) ?
Upvotes: 2
Views: 215
Reputation: 2952
$(".numeric").each(function(){
$(this).attr('data-pre_value', $(this).val());
});
$(".numeric").bind('keyup', function(){
var pre_value = $(this).attr('data-pre_value');
var current_value = $(this).val();
if(pre_value != current_value){
alert('value has changed');
}
});
now, you can change bind event. you can bind event on blur or focus out.
Upvotes: 0
Reputation: 4330
Sorry. Finally i find the best solution. I is easy. We can use change function in jquery. It function fire after change the value. That i wanted.
$('.numeric').change(function () {
alert('Changed');
});
Upvotes: 0
Reputation: 74
Using the 'change' trigger will cover also the case when user copy-paste values in your field(s) by mouse actions
$(".numeric").each(function(){
$(this).data("value", $(this).val());
});
$(".numeric").on('change', function(e) {
var currentValue = $(this).val();
var preVal = $(this).data("value");
if(currentValue != preVal) {
preVal = currentValue;
alert("Value changed!");
}
});
Upvotes: 0
Reputation: 62488
very simple:
var currentValue ;
$(".numeric").keydown(function(e) {
currentValue = $(this).val();
});
$(".numeric").keyup(function(e) {
var currentValue = $(this).val();
if(currentValue != previousValue) {
previousValue = currentValue;
alert("Value changed!");
}
});
here is DEMO
Upvotes: 1
Reputation: 318182
How about just changing the selector to match
$(".numeric").on('keyup', function(e) {
if (e.isTrigger) $(this).data('val', this.value);
if(this.value != $(this).data('val')) {
$(this).data('val', this.value);
alert("Value changed!");
}
}).trigger('keyup');
And instead of just copy pasting code from Google, spend a few hours on https://learn.jquery.com/ and learn how it works.
Upvotes: 1
Reputation: 6753
Use .each()
and .data()
for that:
$(".numeric").each(function(){
$(this).data("value", $(this).val());
});
$(".numeric").keyup(function(e) {
var currentValue = $(this).val();
var preVal = $(this).data("value");
alert(preVal);
if(currentValue != preVal) {
$(this).data("value", currentValue);
preVal = currentValue;
alert("Value changed!");
}
});
Try typing 55
in one field, 66
in another, and 77
in another and notice the previous value remains different for each field
Upvotes: 3