109

I have a text input. A value is populated into it when the page loads. If the user changes anything in text box, then I want to get the changed value (the new value) and old value. But calling ELEMENT.value it only returns the changed/new value.

How do I get the old value?

Here is my code:

      <head>
        <script type="text/javascript">
          function onChangeTest(changeVal) {
            alert("Value is " + changeVal.value);
          }
        </script>
      </head>
      <body>
        <form>
          <div>
              <input type="text" id="test" value ="ABS" onchange="onChangeTest(this)">  
          </div>
        </form>
      </body>
John Kary
  • 6,703
  • 1
  • 24
  • 24
CFUser
  • 2,295
  • 5
  • 32
  • 37

11 Answers11

204

You'll need to store the old value manually. You could store it a lot of different ways. You could use a javascript object to store values for each textbox, or you could use a hidden field (I wouldn't recommend it - too html heavy), or you could use an expando property on the textbox itself, like this:

<input type="text" onfocus="this.oldvalue = this.value;" onchange="onChangeTest(this);this.oldvalue = this.value;" />

Then your javascript function to handle the change looks like this:

    <script type="text/javascript">
    function onChangeTest(textbox) {
        alert("Value is " + textbox.value + "\n" + "Old Value is " + textbox.oldvalue);
    }
    </script>
Community
  • 1
  • 1
Gabriel McAdams
  • 56,921
  • 12
  • 61
  • 77
  • 1
    The change that was suggested here is incorrect. First of all, once an alert occurs, the field has lost focus. Any change after that would occur after the onfocus event was fired. Second, the input field's onchange event doesn't fire until its lost focus. – Gabriel McAdams Mar 25 '11 at 17:39
  • 2
    This works better if you're manipulating the value multiple times. The answer above (element.defaultValue) only works once. Up this one :) –  Jul 13 '12 at 15:10
  • @GabrielMcAdams I understood what you are doing.. I have a question: doesn't it should be `onchange="this.oldvalue = this.value;onChangeTest(this);"` What I means first assign value then call function ? – Grijesh Chauhan Jan 30 '14 at 14:39
  • 1
    @GrijeshChauhan: No. We're setting the old value on focus. After that, after every change, we set it again. – Gabriel McAdams Jan 30 '14 at 16:52
  • A more precise and better answer, since the user can change the value of a textbox multiple times so we need to revert it at every instance – sohaiby Apr 22 '15 at 08:56
  • This works for me on select tag – Imran Mohammed Mar 31 '20 at 17:57
  • at least in firefox, onfocus is skipped in a number field when you directly click on a directional arrow to change the number. onchange fires, causing oldvalue to be undefined. this messy workaround seems to work: onchange="if(typeof this.oldValue == \'undefined\'){this.oldValue=this.defaultValue;}callSomeFn(this.value, this.oldValue);this.oldValue=this.value;" – GregCatalano Nov 03 '20 at 19:03
  • Use [`data` attributes](/q/30417852/4642212) and [`dataset`](//developer.mozilla.org/docs/Web/API/HTMLElement/dataset) or [`Map`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map) (storing _Element → old value_) instead of storing an arbitrary property on elements. – Sebastian Simon Aug 24 '21 at 16:27
83

element.defaultValue will give you the original value.

Please note that this only works on the initial value.

If you are needing this to persist the "old" value every time it changes, an expando property or similar method will meet your needs

Brett Weber
  • 1,839
  • 18
  • 22
George
  • 7,864
  • 5
  • 29
  • 25
  • just a note. I discovered on firefox element.getAttribute("value") also seems to reveal the original... I don't know enough to tell if this is a cross-browser/standard thing. – cheshirekow Oct 15 '10 at 19:32
  • 57
    element.defaultValue returns the value set in the tag. If this value has changed by editing or some other JavaScript, element,defaultValue will not return this (new) old value. – SabreWolfy Jan 23 '12 at 12:59
  • Thanks SabreWolfy, spotted your comment and solved my problem. Had to change the value multiple times so doing the above was no good. –  Jul 13 '12 at 15:11
7

You should use HTML5 data attributes. You can create your own attributes and save different values in them.

tiwari.vikash
  • 367
  • 3
  • 6
6

I would suggest:

function onChange(field){
  field.old=field.recent;
  field.recent=field.value;

  //we have available old value here;
}
krsnik
  • 69
  • 1
  • 1
3

You can do this: add oldvalue attribute to html element, add set oldvalue when user click. Then onchange event use oldvalue.

<input type="text" id="test" value ="ABS" onchange="onChangeTest(this)" onclick="setoldvalue(this)" oldvalue="">

<script>
function setoldvalue(element){
   element.setAttribute("oldvalue",this.value);
}

function onChangeTest(element){
   element.setAttribute("value",this.getAttribute("oldvalue"));
}
</script>
3

A dirty trick I somtimes use, is hiding variables in the 'name' attribute (that I normally don't use for other purposes):

select onFocus=(this.name=this.value) onChange=someFunction(this.name,this.value)><option...

Somewhat unexpectedly, both the old and the new value is then submitted to someFunction(oldValue,newValue)

Curtis
  • 101,612
  • 66
  • 270
  • 352
Jon
  • 47
  • 1
2

I am not sure, but maybe this logic would work.

var d = 10;
var prevDate = "";
var x = 0;
var oldVal = "";
var func = function (d) {
    if (x == 0 && d != prevDate && prevDate == "") {
        oldVal = d;
        prevDate = d;
    }
    else if (x == 1 && prevDate != d) {
        oldVal = prevDate;
        prevDate = d;
    }
    console.log(oldVal);
    x = 1;
};
/*
         ============================================
         Try:
         func(2);
         func(3);
         func(4);
*/
Atombit
  • 953
  • 9
  • 12
Manjeet
  • 949
  • 14
  • 23
2

Maybe you can try to save the old value with the "onfocus" event to afterwards compare it with the new value with the "onchange" event.

ownking
  • 1,956
  • 1
  • 24
  • 34
0

Maybe you can store the previous value of the textbox into a hidden textbox. Then you can get the first value from hidden and the last value from textbox itself. An alternative related to this, at onfocus event of your textbox set the value of your textbox to an hidden field and at onchange event read the previous value.

Canavar
  • 47,715
  • 17
  • 91
  • 122
  • 2
    But, If we have some 100+ text boxes, in this case we need to have 100+ hidden variables, So is there any other way we can get old values? – CFUser Dec 15 '09 at 20:06
0

Probably not the best solution, but as a workaround, tried in ReactJS with Material-UI (MUI). For a text input and using the onChange method, the initial value gets stored into:

event.srcElement._wrapperState.initialValue

And the previous value gets stored into:

event.target.attributes.value.value

The new value can be extracted as standard from:

event.target.value
CVname
  • 347
  • 3
  • 12
0

This is an old post, I am sharing this for knowledge.

What I did so far is that I use element.defaultValue to get the old value, now the defaultValue always returns the value that was set in the value attribute, so when you do a successful change, just store the new value in the element value attribute:

element.setAttribute('value', [new value]);

Now what's interesting, is that element.defaultValue now returns the set value, and if for any reason you want to return to the old value before doing this setAttribute, you simply:

element.value = element.defaultValue;