Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Change event on an <input> element - any way to retain previous value?

I've been searching around this morning and I'm not finding any simple solutions... basically, I want to capture a change in an input element, but also know the previous value.

Here's a change event and an input element in its simplest form. Clearly, I can get the new value with $(elem).val(), but is there a sneaky method I'm missing for getting the previous value? I don't see anything in the jQuery API to do this, but maybe someone's already done this and has some tips?

<script>     $(document).ready(function(){         $('#myInputElement').bind('change', function(){             //var oldvalue = ???             var newvalue = $(this).val();         });     }); </script> <input id="myInputElement" type="text"> 

I'm not against writing my own solution, I just want to make sure I'm not recreating the wheel here.

like image 904
SeanW Avatar asked Jul 21 '09 13:07

SeanW


1 Answers

A better approach is to store the old value using .data. This spares the creation of a global var which you should stay away from and keeps the information encapsulated within the element. A real world example as to why Global Vars are bad is documented here

e.g

<script>     //look no global needed:)      $(document).ready(function(){         // Get the initial value        var $el = $('#myInputElement');        $el.data('oldVal',  $el.val() );          $el.change(function(){             //store new value             var $this = $(this);             var newValue = $this.data('newVal', $this.val());        })        .focus(function(){             // Get the value when input gains focus             var oldValue = $(this).data('oldVal');        });     }); </script> <input id="myInputElement" type="text"> 
like image 192
redsquare Avatar answered Oct 04 '22 13:10

redsquare