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 (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.
please don't use a global var for this - store the prev value at the data here is an example: http://jsbin.com/uqupu3/2/edit
the code for ref:
just saw that you have many selects on page - this approach will also work for you since for each select you will store the prev value on the data of the select
How about using a custom jQuery event with an angular watch type interface;
keep the currently selected drop down value with chosen jquery in a global variable before writing the drop down 'on change' action function. If you want to set previous value in the function you can use the global variable.
I'd like to contribute another option to solve this issue; since the solutions proposed above did not solve my scenario.
This does use jQuery so that def. is a dependency here, but this can be adapted to work in pure javascript. (Add a listener to the body, check if the original target was a select, execute function, ...).
By attaching the change listener to the body, you can pretty much be sure this will fire after specific listeners for the selects, otherwise the value of 'data-previous' will be overwritten before you can even read it.
This is of course assuming that you prefer to use separate listeners for your set-previous and check-value. It fits right in with the single-responsibility pattern.
Note: This adds this 'previous' functionality to all selects, so be sure to fine-tune the selectors if needed.
There are several ways to achieve your desired result, this my humble way of doing it:
Let the element hold its previous value, so add an attribute 'previousValue'.
Once initialized, 'previousValue' could now be used as an attribute. In JS, to access the previousValue of this select:
After you are done using 'previousValue', update the attribute to current value.