views:

170

answers:

2

there is a dropdown with 5 options. Currently,option 2 is selected.The user selects option 4 now.The onchange event gets fired which is caught in a JS function listening for onchange on the select.

In the JS function, I can check easily the index of the option selected by the user using the selectedIndex property.However, I want to also know what was the original value that the user changed it from.

Is there a property that persists basically the original value i.e. option 2 in this case.

A: 

No, you would need to persist that yourself in a js variable.

dl
+1  A: 

Just as a concept I put together the following - there may very well be a better way to do this:

var vals = [];

document.getElementById("colors").onchange = function(){
   vals.unshift(this.selectedIndex);
};

function getPrevious(){
  alert(vals[1]); // you'll need more logic here
                  // this is purposefully simplistic
}

--

<select id="colors">
   <option>Red</option>
   <option>Green</option>
   <option>Blue</option>
</select>

Closed-up Example:

I've tried to tie this all into the actual drop-down element itself. In all honesty, this is the first time I've ever add functions to the dropdown itself, so I cannot promise that this won't have consequences:

   var colors = document.getElementById("colors");
       colors.vals = [];
       colors.setPrevious = function() { this.vals.unshift(this.selectedIndex); }
       colors.getPrevious = function() { return this.vals[1]; }
       colors.onchange    = function() { this.setPrevious(); this.getPrevious(); }
       // set initial state
       colors.setPrevious();
Jonathan Sampson
+1: Good idea. You could use an object instead of an array to handle multiple select elements. Something like `vals = { select : [], select2 : [] }`.
Joel Potter
++1. Assuming they're not always some known default, you'd need to seed vals with initial values as the page loads. Instead of a JS variable to store these (or a hash of them), you could simply store it as an expando on the SELECT tag itself. <select id="colors" initialval="3"> etc. The onchange handler would be essentially the same, though you'd probably need to convert that scalar string to an array the first time the user changes it, but this gives you a convenient place to tuck the old value without cluttering the global namespace -- and an easy way to record the initial selected index.
pluckyglen
Admittedly, some people do have aesthetic issues with "expandos", but if you keep them lowercase in accordance with DOM standards, you shouldn't have a problem using them in any browser.
pluckyglen
looks neat to me.
Rajat