Forget about generating events like keystrokes. Though you can (in various non-portable ways) create events and route them into the event handling system, this will only cause the appropriate event handler functions to be called; it will not make the browser perform the default actions for a user-generated action like a keystroke or mouse click.
In any case, the behaviour you are talking about with resetting on Escape is an IE quirk: in no other browser does Escape have any effect, and even in IE it's unreliable. Specifically, in a normal form, one Escape press loses changes since the last focus, and two Escape presses in a row resets the entire form to initial values. However, if the form has an <input type="reset">
in it, a single Escape press resets the form and focuses the reset button. This makes it even easier to accidentally lose everything you've typed and is another good reason not to include a reset button in your forms.
So, if you want to reset to the initial values, you can call form.reset()
. If you want to reset just one field, you can set input.value= input.defaultValue
(or input.checked= input.defaultChecked
for checkboxes/radios, and similarly defaultSelected
on options).
If, however, you want the value that was present at the time the field was last focused, as IE behaves when there is no reset button, you will have to do some variable-remembering, eg.:
var undonevalue= $('#undoable').val();
$('#undoable').focus(function() {
undonevalue= $('#undoable').val();
});
$('#undoer').click(function() {
$('#undoable').val(undonevalue);
});