views:

1760

answers:

3

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

A: 

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
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
+7  A: 

element.defaultValue will give you the original value.

George
This Worked Very well, Thanks George
CFUser
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
+1  A: 

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)" />

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>
Gabriel McAdams
I can understand you voting an answer down if it doesn't work, or if its an inappropriate answer. I provided an answer that solved the user's need. This code was tested. It is complete. And it does something the accepted answer doesn't (you can always look at the defaultValue property, but what if the user changes the value more than once?).
Gabriel McAdams