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

Asked
Active3 hr before
Viewed126 times

7 Answers

valueinputchangeevent
90%

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,You can store the old value in the change event.,I'm not against writing my own solution, I just want to make sure I'm not recreating the wheel here. ,Connect and share knowledge within a single location that is structured and easy to search.

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">
load more v
88%

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?,I recomend you always declare the "event" object in your event handler functions and inspect them with firebug (console.log(event)) or something. You will find a lot of useful things there that will save you from creating/accessing jquery objects (which are great, but if you can be faster...),Every DOM element has an attribute called defaultValue. You can use that to get the default value if you just want to compare the first changing of data.

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">
load more v
72%

You can store the old value in the change event.,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. ,Every DOM element has an attribute called defaultValue. You can use that to get the default value if you just want to compare the first changing of data., 1 I learn something new every day about jQuery... this is the first I've seen of .data() so I'll definitely read more about it today. – SeanW Jul 21 '09 at 13:44

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">
load more v
65%

Note: it is generally more efficient to use a delegated event handler when there can be multiple matching elements. This way only a single handler is added (smaller overhead and faster initialisation) and any speed difference at event time is negligible.,*Note: A a general rule, use document as the default for delegated events and not body. body has a bug, to do with styling, that can cause it to not get bubbled mouse events. Also document always exists so you can attach to it outside of a DOM ready handler 🙂,Here is the same example using delegated events connected to document:,Delegated events work by listening for an event (focusin, change etc) on an ancestor element (document* in this case), then applying the jQuery filter (input) to only the elements in the bubble chain then applying the function to only those matching elements that caused the event.

$('input').on('focusin', function() {
   console.log("Saving value " + $(this).val());
   $(this).data('val', $(this).val());
});

$('input').on('change', function() {
   var prev = $(this).data('val');
   var current = $(this).val();
   console.log("Prev value " + prev);
   console.log("New value " + current);
});
load more v
75%

Last Updated : 03 Aug, 2021,JQuery | Set the value of an input text field,Set the value of an input field in JavaScript,How to get the value of text input field using JavaScript?

Return the value attribute:
$(selector).val()
load more v
40%

Related Post: Capture value changes in JavaScript using onchange attribute,To distinguish between values inside many input boxes, it is always advisable to assign an id to every element. Now, if you add more input boxes, each with a unique id, then we can use $('#id') as the Selector to capture the changes made in all the input boxes., In the above example, (using input box), we have used two different methods to capture the changes in an element. We can apply similar procedures to get the changed or selected values, that is, either using $('#element') as selector or the $('#id') as a selector.,Since there is only one element, the .change() method will detect and alert any changes made inside the lone input box. However, this procedure (using 'input' as selector) may not produce a desired result if we have more than one input element. There is an alternative to this issue, that is using the id as Selector.

<html>

<head>
   <title>jQuery .change() Method example</title>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>

<body>
   <input type="text" id="t" value="" />
</body>
load more v
22%

I have tried setting the data attribute with the old value to the select element but for some reason it does not get updated with the jQuery data() function.,I have a problem getting the previous/old value of the select element on the change (or changed.bs.select) event. What would be the way to do it?,I've also tried creating a JS function that would set the previous value and set that to the onfocus attribute of the select, like so:,I don't want to use tricks like the following since I have many select elements in one page and I want to use the same event for all of them:

var previous;

$("select").on('focus', function() {
   previous = this.value;
}).change(function() {
   alert(previous);
   previous = this.value;
});
load more v

Other "value-input" queries related to "JQuery Change event on an <input> element - any way to retain previous value?"