Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rollback SELECT change with jQuery

I want a user to be able to confirm a selection they make in a select control, or to rollback to the previous value if they cancel. The following works fine in Chrome/Safari, but no matter what I try, I can't get it to work in Firefox (on Mac).

HTML:

<select id='my-select'>
<option value="client">Client</option>
<option selected="selected" value="assistant">Assistant</option>
<option value="manager">Manager</option>
</select>

JS:

$('#my-select').focus(function() {
    //Store old value
    $(this).data('lastValue',$(this).val());
});
$('#my-select').change(function(e) {

    var lastRole = $(this).data('lastValue');
    var newRole = $(this).val();

    if(confirm("Change user's role from "+lastRole+" to "+newRole+"?"))
    {
        // The control may remain in focus, so we update lastValue here: 
       $(this).data('lastValue',newRole);

        // Do stuff
    }
    else {
        $(this).val(lastRole);
    }
});​

Fiddle: http://jsfiddle.net/yxzqY/13/


The issue can be demonstrated as follows:

  1. Select 'Manager'
  2. Click 'Cancel' (Selected value = 'Assistant')
  3. Select 'Manager' again
  4. Click 'Cancel' (Selected value = 'Assistant' in Chrome, Selected value = 'Manager' in FireFox)

I'm just stumped- no idea how to get this working in Firefox, or how to resolve the diff behavior across browsers.

like image 266
Yarin Avatar asked Dec 20 '22 21:12

Yarin


1 Answers

Why do you need focus event? I think the problem with Firefox is that focus event fires also when you choose element from the dropdown menu before actual change event.

I think you do not need to overcomplicate your code. Try to change focus event to default initialization of data value. Something like this:

$('#my-select').each(function() {
    $(this).data('lastValue', $(this).val());
});

And it should work fine.

DEMO: http://jsfiddle.net/yxzqY/17/

like image 161
VisioN Avatar answered Dec 23 '22 10:12

VisioN