Cancel undo SELECT using jQuery

I want the user to be able to confirm the choices they make in the select control, or roll back to the previous value if they are canceled. It works fine in Chrome / Safari, but no matter what I try, I cannot 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 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);
    }
});​

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


The problem can be demonstrated as follows:

  • Select "Manager"
  • Click "Cancel" (selected value = "Helper")
  • Select "Manager" again
  • Click "Cancel" (selected value = "Helper" in Chrome , selected value = "Manager" in FireFox )

- , Firefox, diff .

+3
2

focus? , Firefox , focus change.

, . focus . - :

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

.

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

+9

, . , Firefox, . , .

, $(this).blur(); .

http://jsfiddle.net/yxzqY/16/

$('#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 role from "+lastRole+" to "+newRole+"?"))
    {
        // Do stuff
    }
    else {
        $(this).val(lastRole);
    }
    // IMPORTANT!: Firefox will not act properly without this:
    $(this).blur();
});
+1

All Articles