Ricardo Binns Ricardo Binns - 7 months ago 18
Javascript Question

input value change detection using class

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.

Answer

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