Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

From a <select> tag, is it possible to find from what value the .change() was triggered?

like image 395
Espen Avatar asked Feb 06 '23 14:02

Espen


2 Answers

Use a variable for 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>
like image 192
Pranav C Balan Avatar answered Feb 08 '23 03:02

Pranav C Balan


Here is a sample, You just have to get the value of the select initially on page load, Then every time there is a change just update this variable with new value.

At any change event the variable currValue holds the previous value before 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>
like image 40
Rajshekar Reddy Avatar answered Feb 08 '23 05:02

Rajshekar Reddy