views:

264

answers:

3

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?

A: 

Just a thought, but can't you not once you handle the change event, set the value to some variable, so next time you handle it, you would have that value?

epitka
If I save it after handling the change event, I won't have the initially selected item and only the subsequent selections. Then in order to get the initial selection, I'd need to make note of it when the document section is loaded.
Alexi Groove
Yes, that would be the case. You would have to get the initial state saved in the variables on when document is loaded.
epitka
+1  A: 

You could do something like this

$(document).ready(function() {
    $("select").each(function(){
     var str = getSelectedText(this);
     $(this).data('selected',str);
    }).change(function () {
     var str = getSelectedText(this);
     var selectedbefore = $(this).data('selected');
     $(this).data('selected',str);
    });
});
function getSelectedText(obj){
    var str = "";
    $(obj).closest('select').find("option:selected").each(function () {
     str += $(this).text() + " ";
    });
    return str;
}
PetersenDidIt
+1  A: 

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');
    });
 });
Greg W
perfect! thanks!
Alexi Groove