Is it possible to find from what value a.change () was called?

From the tag <select>can I find from , what value was called .change()?

+4
source share
3 answers

Use the variable to cache the previous value.

// bind change event handler to the eleemnt 
// and cache the current value in `prev`
var prev = $('#test').change(function() {
  // get previous value from `prev`
  console.log('prev : ' + prev + ' , current : ' + this.value);

  //... do the rest here

  // update the `prev` variable with current value
  prev = this.value;
}).val(); // get the default value
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="test">
  <option value="1">1</option>
  <option value="11">11</option>
  <option value="111">111</option>
</select>
Run codeHide result
+5
source

Here is an example. You just need to get it valuefrom selectthe download page first , then every time there is a change, just update this variable with a new value.

In any change event, the variable currValuecontains the previous value before the change.

var currValue = $('select').val();

$('select').on('change',function(){
  var newValue = $(this).val();
  alert('value Before change : '+ currValue);
  alert('value After change : '+ newValue);
  
  currValue = newValue;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
<select>
Run codeHide result
+2
source

, , :

(function () {
    var previous;

    $("select[name=test]").focus(function () {
        // Store the current value on focus, before it changes
        previous = this.value;
    }).change(function() {
        // Do soomething with the previous value after the change
        document.getElementById("log").innerHTML = "<b>Previous: </b>"+previous;
        
        previous = this.value;
    });
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="test">
    <option value="stack">Stack</option>
    <option value="overflow">Overflow</option>
    <option value="my">My</option>
    <option value="question">Question</option>
</select>
<div id="log"></div>
Hide result
+1
source

Source: https://habr.com/ru/post/1662498/


All Articles