Skip to content

Instantly share code, notes, and snippets.

@pixelhandler
Created July 14, 2011 04:10
Show Gist options
  • Save pixelhandler/1081920 to your computer and use it in GitHub Desktop.
Save pixelhandler/1081920 to your computer and use it in GitHub Desktop.
Hijack form’s submit onclick, validate, and use enter key to post form
// using jQuery library and validation plugin in this code
// for checking keycodes
function getKeyCode(event) {
var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
return keycode;
}
// is there an anchor as Submit button?
var $submit = $('a[id$="_submit"]');
// is there any behavior already on submit, like -> onclick="__doPostBack(...)"
$submit.action = $submit.attr('onclick');
$submit.click(function(e){
// using jQuery validation plugin to validate
$submit.valid = $('.myform').valid();
if (!$submit.valid) {
e.preventDefault();
} else {
// process original onclick stuff
$($submit.action).trigger('click');
}
});
// submit with enter key
$(".myform input").bind("keydown", function(event) {
// track enter key
var keycode = getKeyCode(event);
// keycode for enter key
if (keycode == 13) {
// force the 'Enter Key' to implicitly click the Sumbit button
$submit.click();
return false;
} else {
return true;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment