Monitoring a value change on an input element

For a recent project I ran into a slight issue with the jQuery change event. It’s not an issue with jQuery, but I was quite surprised when it didn’t work as I expected. I’d set up a selection of form inputs that a user could change; once changed various calculations would be made and the values outputted to a second set of disabled input elements (demo). The inputs are disabled as they are to be calculated rather than entered manually.

I’d attached the jQuery change event to the output elements like so:

1
2
3
$("#outputs").find("input:text").bind("change", function(){
    $(this).highlightFade('red');
});

So the plan was, once an input value had been changed using the jQuery().val() method the change event would fire and it would quickly colour in and out the element (using highlightFade) to notify the user that it’s value had changed. Unfortunately the change event wasn’t firing, so I had to find another way to monitor the output elements.

What I ended up doing was using an array to hold the previous values of the input elements then checking to see if they had changed in the calculation. If changed then fire the event:

1
2
3
4
5
6
7
8
9
10
11
12
13
//Array to store the old values
var oldValues = [];

//Push these values into an array which is checked on calculation
$("#valueOutput input:text").each(function(i){
   var thisValue = $(this).val();
   //If the old value is different to the new, change the colour
   if(oldValues[i] !== thisValue){
       $(this).highlightFade('red');
   }
   //Push the new value into the array
   oldValues[i] = thisValue;
});

It’s quite hard to explain exactly what’s happening so I’ve put together a small demo. Try changing one of the top input fields then tab (or click out) of the input element to recalculate. Is there an easier (or better) way to do this? Comment below.

Loading

Webmentions