1

based in this question:

Jquery input value change detection

i have input 1 and input 2 , with value='100'

if i change the input 1 value, the alert show that the value was change, perfet.

but if i get in the input and lose the focus (i'm working with focusout()) again, the alert will keep showing that the value was changed again, maybe because i'm using a class.

i cant put this to work, what i'm missing ?

html:

<input type="text" value="100" class="inputTest" />
<input type="text" value="100" class="inputTest" />

js:

$(".inputTest").focusout(function(){
   if(this.value != this.defaultValue){
        alert('changed');
    } 
});

made a live example.

Thanks.

Community
  • 1
  • 1
Ricardo Binns
  • 3,228
  • 6
  • 44
  • 71
  • are you looking for `defaultValue()` and `val()` – run Nov 17 '11 at 13:51
  • 1
    I'm not quite sure, what the problem is. The alert will always fire if the value is different from 100. If you want to test if the new value differs from the previous one, you need a variable to hold the present value. Or you use a MVC Framework (if you're project is bigger and you need a lot of this.) – Johannes Klauß Nov 17 '11 at 13:55

4 Answers4

3

Use the data() method to store the last value put into the input. You can then change your logic to test against this, rather than the default value.

$(".inputTest").each(function() {
    $(this).data("lastValue", this.value);
})

$(".inputTest").focusout(function() {
    if (this.value != $(this).data("lastValue")) {
        alert('changed');
        $(this).data("lastValue", this.value)
    }
});

Fiddle here

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

Perhaps you should use the change handler instead of the focusout handler. That way it will only check the values if the value was changed.

bozdoz
  • 12,550
  • 7
  • 67
  • 96
1

The issue is that you test for value != defaultValue on focusout, this will obviously never be true once the value has been changed once, until it is changed again.

You need to check whether this.value != this.previousValue, and store the previous value of the field in some way.

EDIT: @Rory McCrossan has described exactly how to do this in his answer.

ankit
  • 3,328
  • 3
  • 26
  • 39
1

defaultValue will always contain 100. If you change the content of the input box, the defaultValue will not change.

Consider storing the previous value:

// Initialize previousValue
$(".inputTest").each(function () {
    $(this).data('previousValue', this.defaultValue);
});

$(".inputTest").focusout(function(){
   if(this.value != $(this).data('previousValue')){
        alert('changed');
        // Set previousValue again
        $(this).data('previousValue', this.value);
    } 
});
Sjoerd
  • 74,049
  • 16
  • 131
  • 175