jerrygarciuh wrote:
Hi Jerry,
I have been playing with various Googled solutions for capturing the <Enter>
key to suppress form submission.
You certainly have your reasons to do so, but you're taking a dangerous
way IMHO: users are generally aware of their browsers' behavior, and
altering it in some way may always confuse them rather than enhance
their experience - changing the behavior of the ENTER key would likely
lead to such confusion.
My first question is whether anyone has a script that works in all common
browsers? The script bellow is IE only. It fails FF 1.0 and NN 7.
You won't have this in common to all browsers, since (1) the ENTER key
behavior isn't standard (which means that not all browsers behave this
way) and (2) old browsers used to exhibit the behavior on different key
events (keyup, keydown and keypress) which would require the code to
take into account some sort of key events flow (a nightmare, I've done
this before and it was ugly at best).
However, if targeting recent browsers is acceptable to you, then check
the following simple version (tested IE6, Mozilla 1.7 and Opera 8 and
Windows) - given the general issue it's unlikely to work in all recent
browsers, though - please test accordingly.
---
<form action="foo">
<input type="text" tabindex="1">
<input type="text" tabindex="2">
<input type="text" tabindex="3">
<input type="text" tabindex="4">
<input type="submit">
</form>
<script type="text/javascript">
function enter(form){
var fields=form.elements, a=[];
// add ENTER listeners
for(var ii=fields.length; ii--;) {
if(fields[ii].type=="text") {
_e(fields[ii], "onkeypress", enterListener);
a[a.length]=fields[ii];
}
}
// init the tabIndex behavior
a.sort(
function(a,b){
return a.tabIndex > b.tabIndex ? 1 : -1;
}
);
for(var j=0; j<a.length; j++){
a[j].next = a[j+1]||a[0];
}
// add the submission manager
_e(
form,
"onsubmit",
function(evt){
if(form.hasEntered) {
form.hasEntered=false;
return false;
}
return true;
}
);
// ENTER listener
function enterListener(evt){
evt=evt||window.event;
var el=this;
if((evt.keyCode||evt.which)==13) {
form.hasEntered=true;
setTimeout(
function(){ el.next.focus(); },
1
);
}
}
}
// event manager
function _e(obj, evt, func){
if(obj[evt]) {
obj[evt]=(function(h){
return function(evt){
return func.call(this, evt) && h.call(this, evt);
}
})(obj[evt]);
} else {
obj[evt]=func;
}
}
// --- test --- :-)
enter(document.forms[0]);
</script>
---
Regards,
Yep.