From a <select>
tag, is it possible to find from what value the .change()
was triggered?
Asked
Active
Viewed 38 times
4

Espen
- 3,607
- 11
- 48
- 75
-
cache value in a variable – Pranav C Balan Dec 01 '16 at 07:48
-
Possible duplicate of [Getting value of select (dropdown) before change](http://stackoverflow.com/questions/4076770/getting-value-of-select-dropdown-before-change) – Ryad Boubaker Dec 01 '16 at 07:55
-
@Ryad.iv: To be pedantic, I don't need it before change, but after it has been changed. For this to be a duplicate the earlier post need a title edit. – Espen Dec 01 '16 at 08:15
-
Just to be clear in the example provided by @PranavCBalan what value do you need the prev or the current. – Ryad Boubaker Dec 01 '16 at 08:18
-
2I need the previous value. But the title of the earlier post is ambiguous because you could read it as needing the value of the select before the .change() is fired. – Espen Dec 01 '16 at 08:21
3 Answers
5
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>

Pranav C Balan
- 113,687
- 23
- 165
- 188
2
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>

Rajshekar Reddy
- 18,647
- 3
- 40
- 59
1
If I'm not wrong this is what you are asking for:
(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>

Ryad Boubaker
- 1,491
- 11
- 16