Getting previously selected item in select box with jQuery

Alexi Groove picture Alexi Groove · Dec 4, 2009 · Viewed 15.2k times · Source

I have a single item HTML select box on which I'd like to find out the what item was selected just prior to changing selection to the new item.

By the time the change event is fired, it's already too late:

$("select").change(function () {
  var str = "";
  $("select option:selected").each(function () {
      // this will get me the current selected item (the new one)
      str += $(this).text() + " "; });          
})

The docs say that 'The change event fires when a control loses the input focus and its value has been modified since gaining focus.'

However, trapping the 'blur' event doesn't seem to be the right event either and there's no "onFocusLost" type of event..

Is this feasible in a cross-browser compatible way without a lot of hoop jumping?

Answer

Greg W picture Greg W · Dec 4, 2009

This should capture the value before it changes. The value will be grabbed as soon as the user opens the select menu, but before they actually select something.

        $(document).ready(function(){
            $('select').focus(function(){
                var theValue = $(this).attr('value');
            });
    });