How to get previous and new selected value from a option DOM element with JavaScript?

Using straight JavaScript and DOM, something like this (live example):

var box, oldValue;

// Get a reference to the select box's DOM element.
// This can be any of several ways; below I'll look
// it up by ID.
box = document.getElementById('theSelect');
if (box.addEventListener) {
  // DOM2 standard
  box.addEventListener("change", changeHandler, false);
}
else if (box.attachEvent) {
  // IE fallback
  box.attachEvent("onchange", changeHandler);
}
else {
  // DOM0 fallback
  box.onchange = changeHandler;
}

// Our handler
function changeHandler(event) {
  var index, newValue;

  // Get the current index
  index = this.selectedIndex;
  if (index >= 0 && this.options.length > index) {
    // Get the new value
    newValue = this.options[index].value;
  }

  // **Your code here**: old value is `oldValue`, new value is `newValue`
  // Note that `newValue`` may well be undefined
  display("Old value: " + oldValue);
  display("New value: " + newValue);

  // When done processing the change, remember the old value
  oldValue = newValue;
}

(I'm assuming all of the above is inside a function, like a page load function or similar, as in the live example, so we're not creating unnecessary global symbols [box, oldValue, 'changeHandler`].)

Note that the change event is raised by different browsers at different times. Some browsers raise the event when the selection changes, others wait until focus leaves the select box.

But you might consider using a library like jQuery, Prototype, YUI, Closure, or any of several others, as they make a lot of this stuff a lot easier.


Look here: Getting value of select (dropdown) before change I think the better,

(function () {
    var previous;

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

The following code snippet may help

<html>
    <script type="text/javascript">
        this.previousVal;
        function changeHandler(selectBox)
        {
            alert('Previous Val-->'+selectBox.options[this.previousVal].innerHTML)
            alert('New Val-->'+selectBox.options[selectBox.selectedIndex].innerHTML)
            this.previousVal=selectBox.selectedIndex;
        }
    </script>
    <body>
        <select id="selectBox" onchange="changeHandler(this)">
            <option>Sunday</option><option>Monday</option>
            <option>Tuesday</option><option>Wednesday</option>
        </select>
        <script type="text/javascript">
            var selectBox=document.getElementById("selectBox")
            this.previousVal=selectBox.selectedIndex
        </script>
    <body>
</html>