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:
- Select ‘Manager’
- Click ‘Cancel’ (Selected value = ‘Assistant’)
- Select ‘Manager’ again
- 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.
Why do you need
focusevent? I think the problem with Firefox is thatfocusevent fires also when you choose element from the dropdown menu before actualchangeevent.I think you do not need to overcomplicate your code. Try to change
focusevent to default initialization of data value. Something like this:And it should work fine.
DEMO: http://jsfiddle.net/yxzqY/17/