Search code examples
javascriptjqueryjquery-events

Getting value of select (dropdown) before change


The thing I want to achieve is whenever the <select> 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>
</select>

Lets say currently option My is selected now when I change it to stack in the onchange event (i.e. when I changed it to stack) I want it's previous value i.e. 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.


Solution

  • 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
            alert(previous);
    
            // Make sure the previous value is updated
            previous = this.value;
        });
    })();
    

    Working example: http://jsfiddle.net/x5PKf/766