Getting value of select (dropdown) before change

Getting value of select (dropdown) before change

The thing i want to achieve is whenever the

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.


Solution 1:

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:

Related:  How to get the URL without any parameters in JavaScript?

Solution 2:

please don’t use a global var for this – store the prev value at the data
here is an example:

the code for ref:

  var sel = $("#sel");"prev",sel.val());

     var jqThis = $(this);

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

Solution 3:

I go for Avi Pinto’s solution which uses

Using focus isn’t a valid solution. It works at first time you change the options, but if you stay on that select element, and press key “up” or “down”. It won’t go through the focus event again.

So the solution should be more looks like the following,

//set the pre data, usually needed after you initialize the select element
$('mySelect').data('pre', $(this).val());

    var before_change = $(this).data('pre');//get the pre data
    //Do your work here
    $(this).data('pre', $(this).val());//update the pre data

Solution 4:

Track the value by hand.

var selects = jQuery("select.track_me");

selects.each(function (i, element) {
  var select = jQuery(element);
  var previousValue = select.val();
  select.bind("change", function () {
    var currentValue = select.val();

    // Use currentValue and previousValue
    // ...

    previousValue = currentValue;

Solution 5:

 $("#dropdownId").on('focus', function () {
    var ddl = $(this);'previous', ddl.val());
}).on('change', function () {
    var ddl = $(this);
    var previous ='previous');'previous', ddl.val());

Solution 6:

I am using event “live”, my solution is basically similiar with Dimitiar, but instead of using “focus”, my previous value is stored when “click” is triggered.

var previous = "initial prev value";
$("select").live('click', function () {
        //update previous value
        previous = $(this).val();
    }).change(function() {
        alert(previous); //I have previous value