Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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> 
like image 300
CFUser Avatar asked Dec 15 '09 20:12

CFUser


People also ask

How do you find the value of old?

To get old value with onchange() event in text box with JavaScript, we can get the old value when the click event is emitted. const input = document. querySelector("input"); input. onclick = (e) => { e.

How do you get an event on Onchange?

The onchange event occurs when the value of an element has been changed. For radiobuttons and checkboxes, the onchange event occurs when the checked state has been changed. Tip: This event is similar to the oninput event.

How do I use Onchange input field?

The onchange attribute fires the moment when the value of the element is changed. Tip: This event is similar to the oninput event. The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus.

Can I use Onchange in select tag?

Yes. Add an onChange property to the first select, then use it to call a javascript function you have written elsewhere.


1 Answers

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> 
like image 131
Gabriel McAdams Avatar answered Sep 20 '22 10:09

Gabriel McAdams