Alpesh Alpesh - 9 months ago 133
Javascript Question

Getting value of select (dropdown) before change

The thing i want to achieve is whenever the

dropdown is changed i want the value of the dropdown before change. I am using 1.3.2 version of jquery and using on change event but the value i am getting over there is after change.

<select name="test">
<option value="stack">Stack</option>
<option value="overflow">Overflow</option>
<option value="my">My</option>
<option value="question">Question</option>

Lets say currently option My is selected now when i change it to stack in the onchange event (ie when i changed it to stack) i want it's previous value ie my expected in this case.

How can this be achieved ?

Edit: In my case i am having multiple select boxes in the same page and want same thing to be applied to all of them. Also all of my select are inserted after page load through ajax.


Combine the focus event with the change event to achieve what you want:

(function () {
    var previous;

    $("select").on('focus', function () {
        // Store the current value on focus and on change
        previous = this.value;
    }).change(function() {
        // Do something with the previous value after the change

        // Make sure the previous value is updated
        previous = this.value;

Working example: