Input jQuery get old value before onchange and get value after on change

JavascriptJqueryHtml

Javascript Problem Overview


I have an input text in jQuery I want to know if it possible to get the value of that input text(type=number and type=text) before the onchange happens and also get the value of the same input input text after the onchange happens. This is using jQuery.

What I tried:

I tried saving the value on variable then call that value inside onchange but I am getting a blank value.

Javascript Solutions


Solution 1 - Javascript

The simplest way is to save the original value using data() when the element gets focus. Here is a really basic example:

JSFiddle: http://jsfiddle.net/TrueBlueAussie/e4ovx435/

$('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);
});

Better to use Delegated Event Handlers

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.

Here is the same example using delegated events connected to document:

$(document).on('focusin', 'input', function(){
    console.log("Saving value " + $(this).val());
    $(this).data('val', $(this).val());
}).on('change','input', function(){
    var prev = $(this).data('val');
    var current = $(this).val();
    console.log("Prev value " + prev);
    console.log("New value " + current);
});

JsFiddle: http://jsfiddle.net/TrueBlueAussie/e4ovx435/65/

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.

*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 :)

Solution 2 - Javascript

Definitely you will need to store old value manually, depending on what moment you are interested (before focusing, from last change). Initial value can be taken from defaultValue property:

function onChange() {
    var oldValue = this.defaultValue;
    var newValue = this.value;
}

Value before focusing can be taken as shown in Gone Coding's answer. But you have to keep in mind that value can be changed without focusing.

Solution 3 - Javascript

Just put the initial value into a data attribute when you create the textbox, eg

HTML

<input id="my-textbox" type="text" data-initial-value="6" value="6" /> 

JQuery

$("#my-textbox").change(function () {
 var oldValue = $(this).attr("data-initial-value");
 var newValue = $(this).val();
});

Solution 4 - Javascript

I have found a solution that works even with "Select2" plugin:

function functionName() {
  $('html').on('change', 'select.some-class', function() {
    var newValue = $(this).val();
    var oldValue = $(this).attr('data-val');
    if ( $.isNumeric(oldValue) ) { // or another condition
      // do something
    }
    $(this).attr('data-val', newValue);
  });
  $('select.some-class').trigger('change');
}

Solution 5 - Javascript

I found this question today, but I'm not sure why was this made so complicated rather than implementing it simply like:

var input = $('#target');
var inputVal = input.val();
input.on('change', function() {
  console.log('Current Value: ', $(this).val());
  console.log('Old Value: ', inputVal);
  inputVal = $(this).val();
});

If you want to target multiple inputs then, use each function:

$('input').each(function() {
  var inputVal = $(this).val();
  $(this).on('change', function() {
    console.log('Current Value: ',$(this).val());
    console.log('Old Value: ', inputVal);
    inputVal = $(this).val();
});

Solution 6 - Javascript

my solution is here

function getVal() {
    var $numInput =  $('input');
    var $inputArr = [];
    for(let i=0; i < $numInput.length ; i++ ) 
       $inputArr[$numInput[i].name] = $numInput[i].value;
    return $inputArr;
}
var $inNum =  getVal();
$('input').on('change', function() {
    // inNum is last Val
    $inNum =  getVal(); 
    // in here we update value of input
    let $val = this.value;      
});

Solution 7 - Javascript

The upvoted solution works for some situations but is not the ideal solution. The solution Bhojendra Rauniyar provided will only work in certain scenarios. The var inputVal will always remain the same, so changing the input multiple times would break the function.

The function may also break when using focus, because of the ▲▼ (up/down) spinner on html number input. That is why J.T. Taylor has the best solution. By adding a data attribute you can avoid these problems:

<input id="my-textbox" type="text" data-initial-value="6" value="6" />

Solution 8 - Javascript

If you only need a current value and above options don't work, you can use it this way.

$('#input').on('change', () => {
  const current = document.getElementById('input').value;
}

Solution 9 - Javascript

My business aim was removing classes form previous input and add it to a new one.
In this case there was simple solution: remove classes from all inputs before add

<div>
   <input type="radio" checked><b class="darkred">Value1</b>
   <input type="radio"><b>Value2</b>
   <input type="radio"><b>Value3</b>
</div>

and

$('input[type="radio"]').on('change', function () {
   var current = $(this);
   current.closest('div').find('input').each(function () {
       (this).next().removeClass('darkred')
   });
   current.next().addClass('darkred');
});

JsFiddle: http://jsfiddle.net/gkislin13/tybp8skL

Solution 10 - Javascript

if you are looking for select droplist, and jquery code would like this:

var preValue ="";
//get value when click select list
$("#selectList").click(
	function(){
		preValue =$("#selectList").val();
	}
);

$("#selectList").change(
	function(){
		var curentValue = $("#selectList").val();
        var preValue = preValue;
        console.log("current:"+curentValue );
        console.log("old:"+preValue );
	}
);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPekkaView Question on Stackoverflow
Solution 1 - JavascriptGone CodingView Answer on Stackoverflow
Solution 2 - JavascriptmashiView Answer on Stackoverflow
Solution 3 - JavascriptJ.T. TaylorView Answer on Stackoverflow
Solution 4 - JavascriptthapachakiView Answer on Stackoverflow
Solution 5 - JavascriptBhojendra RauniyarView Answer on Stackoverflow
Solution 6 - JavascriptEhsanView Answer on Stackoverflow
Solution 7 - JavascriptJohn Andrew SanchiricoView Answer on Stackoverflow
Solution 8 - JavascriptBrayan Steven Martínez VanegasView Answer on Stackoverflow
Solution 9 - JavascriptGrigory KislinView Answer on Stackoverflow
Solution 10 - JavascriptLiang WuView Answer on Stackoverflow