Ajax.BeginForm + prevent submit on enter
I'm using ASP.NET MVC 3 with unobstrusive ajax and I would like to prevent submit form by enter. I wrote the following code to do that
$(window).keypress(functi开发者_运维问答on (event) {
if (event.which == 13) {
event.preventDefault();
}
});
Unfortunately this event is not triggered on IE8. Is there any other options. (I'm using jQuery 1.6.4)
You should set focus on next element in DOM
$(window).keypress(function (event) {
if (event.which == 13) {
$(this).next().focus();
}
});
Check the next element type, if the type is not a textarea (enters permitted), or button/submit (enter = click) then we just tab to the next thing.
example,
if (e.which == 13) {
var $targ = $(e.target);
if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
var focusNext = false;
$(this).find(":input:visible:not([disabled],[readonly]), a").each(function(){
if (this === e.target) {
focusNext = true;
}
else if (focusNext){
$(this).focus();
return false;
}
});
return false;
}
}
Check this to make sure that you key press or key down even gets picked up in your browser. If you don't want that event to return anything, then simply return false;
EDIT: Oh, just reread your question - in IE you probably want to target $(window).keydown(function(event)
instead of keypress
I think in IE, you have to look at the event.keyCode property
$(window).keypress(function (event) {
if(event && event.which){ //if which property of event object is supported (NN4)
characterCode = event.which //character code is contained in NN4's which property
}
else{
characterCode = event.keyCode //character code is contained in IE's keyCode property
}
if (characterCode == 13){
event.preventDefault();
}
精彩评论