[javascript] Input jQuery get old value before onchange and get value after on change

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.

This question is related to javascript jquery html

The answer is


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;      
});

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.


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


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;
}

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

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

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


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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment