How to get old Value with onchange() event in text box

CFUser picture CFUser · Dec 15, 2009 · Viewed 227.2k times · Source

I have a text Box and a Value poplulated in it when page loads. Now If user chanegs any thing in text box, then I want to get the Changed Value(New Value) and Old Value but when I do ELEMENT.value then its giving only changed Value

any Suggestions to get old value?

below 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>
</html>

Thanks in Advance

Answer

Gabriel McAdams picture Gabriel McAdams · Dec 15, 2009

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>