Detecting and Processing the <Enter> Key ?

M

Mel Smith

Hi:

My clients wish to use the <Enter> key to proceed forward from input
text field to next input text field, etc . I *know* that <Tab> is more
properly used for this purpose, but the users should be satisfied before me
:(

I would like some guidance on creating a Javascript function in the
<head> section, that would be called in an <input> section with the
onkeydown="myenterkeyfunction". If the function detects an <enter> key focus
is advanced, if not, the key will be allowed its default action.

Can anyone help ??

btw, I'm looking at my reference (JavaScript - The Definitive Guide 5th
Edition by David flanagan) and found what looks appropriate but it is too
complex for my understanding ). It is in Chapeter 17, and is Example 17-6 -
'a Keymap class for keyboard shortcuts'

Can anyone provide a simple function and calling method for detecting
the <Enter> key (13), and setting focus to next input text field ??

Thanks for some further understanding of this 'keyboard events' issue
 
M

Mel Smith

Hi:

During the past couple of hours I 'surfed around' and found the
following solution to my <Enter> key activation:

<BODY>

<FORM name="frmregister' METHOD="POST">

Name: <INPUT TYPE="TEXT" name="fullname" onKeyDown="if(event.keyCode==13)
event.keyCode=9;"><BR>

Address: <INPUT TYPE="TEXT" name="address" onKeyDown="if(event.keyCode==13)
event.keyCode=9;"><BR>

City: <INPUT TYPE="TEXT" name="city" onKeyDown="if(event.keyCode==13)
event.keyCode=9;"><BR>

<!-- etcetera -->

</FORM>

The above solution apparently changes a <enter> key to a <Tab> key --
which is good and moves focus to the next input field nicely

However, I may wish to 'jump over' or bypass some fields. So I tried the
following construction:

onkeydown="if(event.keyCode--13) document.frmregister.city.focus();"
<!-- jumping over some fields to a new field --->

If this 'jump far' to a new field clause above syntactically correct ?
Or is it even possible to do this ??

Thanks for any further help.

-Mel Smith
 
T

Trevor Lawrence

Mel Smith said:
Hi:

During the past couple of hours I 'surfed around' and found the
following solution to my <Enter> key activation:

<BODY>

<FORM name="frmregister' METHOD="POST">

Name: <INPUT TYPE="TEXT" name="fullname" onKeyDown="if(event.keyCode==13)
event.keyCode=9;"><BR>

Address: <INPUT TYPE="TEXT" name="address"
onKeyDown="if(event.keyCode==13) event.keyCode=9;"><BR>

City: <INPUT TYPE="TEXT" name="city" onKeyDown="if(event.keyCode==13)
event.keyCode=9;"><BR>

<!-- etcetera -->

</FORM>

The above solution apparently changes a <enter> key to a <Tab> key --
which is good and moves focus to the next input field nicely

However, I may wish to 'jump over' or bypass some fields. So I tried
the following construction:

onkeydown="if(event.keyCode--13)
document.frmregister.city.focus();" <!-- jumping over some fields to a new
field --->

If this 'jump far' to a new field clause above syntactically correct ?
Or is it even possible to do this ??

Well, I fiddled around a bit and came up with this

<form id="frmregister" method="post">
Name: <input type="text" id="fullname"
onkeypress="if (event.keyCode==13)
forms.frmregister.city.focus();"><br>
Address: <input type="text" id="address"
onKeyDown="if(event.keyCode==13) event.keyCode=9;"><br>
City: <input type="text" id="city" ><br>
</form>

I used id= instead of name=

Pressing enter in "fullname" tabs to "city"
Pressing enter in "address" tabs to "city"

When I use onKeyDown= in "fullname" this also tabs to "city"
When I use onkeypress= in "address" it does NOT tab to "city"
Since this is a JavaScript group, no doubt the experts will tell us why, but
it looks as if onKeyDown is the safer option
 
M

Mel Smith

Trevor & Joao:

I guess tomorrow, I'll start using all combos and see if I can come up
with a proper 'jump/skip' thru Text Fields.

I read (somewhere) that 'onkeydown' was more reliable than
'onkeypress' -- especially on older versions of IE (<IE7 )

Thanks for your comments and guidance

Please let me know if you find the 'Holy Grail' of this problem :))

-Mel Smith
Mesa, Arizona
 
M

Mel Smith

Trevor & Joao:

I re-did Trevor's testexample and now (using IE7) I can't make *any*
combination work to get the <enter> key to move forward.

Could you please copy this example to your machine, and tell me what to
change to make it work ??

Thanks !

-Mel Smith
Mesa, Arizona

------- Simple html test to use at the command prompt: C:\> explorer
thisnextcode.htm ----
<html>
<head>
<title>Enter-Key Problem</title>
</head>

<!-- MWS Feb 1/09 Now, *nothing* works. Even if I use
the onKeyDown event, I still go right to 'Submit'
Can someone take this code and make it work Please ?? -->

<body onload="forms.frmregister.firstname.focus();">

<form id="frmregister" method="POST">

<input type="text" id="firstname" value="Trevor"
onKeyPress="if(event.keyCode==13,forms.frmregister.surname.focus();">
<br />

<input type="text" id="surname" value="Lawrence"
onKeyPress="if(event.keyCode==13,forms.frmregister.address.focus();">
<br />

<input type="text" id="address" value="123 SomeStreet"
onKeyPress="if(event.keyCode==13,forms.frmregister.city.focus();">
<br />

<input type="text" id="city" value="City of Hope"
onKeyPress="if(event.keyCode==13,forms.frmregister.state.focus();">
<br />

<input type="text" id="state" value="State of Despair"
onKeyPress="if(event.keyCode==13,forms.frmregister.zipcode.focus();">
<br />

<input type="text" id="zipcode" value="85208"
onKeyPress="if(event.keyCode==13,forms.frmregister.firstname.focus();">
<br />
<br />

<input type="submit" name="submit" value="LOGIN" />

</form>
</html>
 
T

Trevor Lawrence

Mel Smith said:
Trevor & Joao:

I re-did Trevor's testexample and now (using IE7) I can't make *any*
combination work to get the <enter> key to move forward.

Could you please copy this example to your machine, and tell me what to
change to make it work ??

Thanks !

-Mel Smith
Mesa, Arizona

Mel,
Each of your lines was of this format

<input type="text" id="address" value="123 SomeStreet"
onKeyPress="if(event.keyCode==13,forms.frmregister.city.focus();">
<br />

w3schools spells these keywords as onkeypress and onkeydown. I think I used
onkeypress and onKeyDown, and you used onKeyPress. Apparently HTML is not
case sensitive whereas JavaScript is.

http://www.w3schools.com/jsref/jsref_onkeydown.asp
http://www.w3schools.com/jsref/jsref_onkeypress.asp

The following difference is well worth noting
Browser differences: Internet Explorer uses event.keyCode to retrieve the
character that was pressed and Netscape/Firefox/Opera uses event.which.
However, your main problem could be the code after onKeyPress (however
spelt)

You have "if(event.keyCode==13,forms.frmregister.city.focus();"
It should be "if(event.keyCode==13) forms.frmregister.city.focus();"

What is in the quotes should be valid JS code and the code should be

if (event.keyCode==13) {
forms.frmregister.city.focus();
}

The braces { and } can be omitted but the test after if must be in ordinary
brackets ( and ) not ( and , as you have

This code works for me. Note that I added an extra function to test for the
difference between IE and FireFox

<html>
<head>
<title>Enter-Key Problem</title>
<script type="text/javascript">
function getNumber(e) {
if(window.event) // IE
return e.keyCode;
else if(e.which) // Netscape/Firefox/Opera
return e.which;
}
</script>
</head>
<body onload="forms.frmregister.firstname.focus();">
<form id="frmregister" method="POST">

<input type="text" id="firstname" value="Trevor"
onKeyDown="if (getNumber(event)==13)
forms.frmregister.surname.focus();"><br>

<input type="text" id="surname" value="Lawrence"
onKeyDown="if (getNumber(event)==13)
forms.frmregister.address.focus();"><br>

<input type="text" id="address" value="123 SomeStreet"
onKeyDown="if (getNumber(event)==13)
forms.frmregister.city.focus();"><br>

<input type="text" id="city" value="City of Hope"
onKeyDown="if (getNumber(event)==13)
forms.frmregister.state.focus();"><br>

<input type="text" id="state" value="State of Despair"
onKeyDown="if (getNumber(event)==13)
forms.frmregister.zipcode.focus();"><br>

<input type="text" id="zipcode" value="85208"
onKeyDown="if (getNumber(event)==13)
forms.frmregister.firstname.focus();"><br>
<!--
<input type="submit" name="submit" value="LOGIN" />
-->
</form>
</body>
</html>

But when I uncomment the submit button, pressing enter in any input box goes
to submit. Don't know why !!
 
M

Mel Smith

Trevor & Joao:

There needs to be a correction below
from: if(event.keyCode==13, Note the incorrect comma'

to: if(event.keyCode==13) Replace with ')'

but even with these corrective changes, still the <enter> key advance
does not work anymore for me :((

------- Simple html test to use at the command prompt: C:\> explorer
thiscodebelow.htm

<!-- The corrections are made below -->
<html>
<head>
<title>Enter-Key Problem</title>
</head>

<!-- MWS Feb 1/09 Now, *nothing* works. Even if I use
the onKeyDown event, I still go right to 'Submit'
Can someone take this code and make it work Please ?? -->

<body onload="forms.frmregister.firstname.focus();">

<form id="frmregister" method="POST">

<input type="text" id="firstname" value="Trevor"
onKeyPress="if(event.keyCode==13)forms.frmregister.surname.focus();">
<br />

<input type="text" id="surname" value="Lawrence"
onKeyPress="if(event.keyCode==13)forms.frmregister.address.focus();">
<br />

<input type="text" id="address" value="123 SomeStreet"
onKeyPress="if(event.keyCode==13)forms.frmregister.city.focus();">
<br />

<input type="text" id="city" value="City of Hope"
onKeyPress="if(event.keyCode==13)forms.frmregister.state.focus();">
<br />

<input type="text" id="state" value="State of Despair"
onKeyPress="if(event.keyCode==13)forms.frmregister.zipcode.focus();">
<br />

<input type="text" id="zipcode" value="85208"
onKeyPress="if(event.keyCode==13)forms.frmregister.firstname.focus();">
<br />
<br />

<input type="submit" name="submit" value="LOGIN" />

</form>
</html>

------------------- end of corrected code -----------
 
T

Trevor Lawrence

Mel Smith said:
Trevor & Joao:

There needs to be a correction below
from: if(event.keyCode==13, Note the incorrect comma'

to: if(event.keyCode==13) Replace with ')'

but even with these corrective changes, still the <enter> key advance
does not work anymore for me :((

Mel,
Yes, that was what I wrote in my post which crossed with yours.

I can get it to work PROVIDED that there is no submit button. Perhaps forms
treat Enter as if it were a submit regardless of how onkeypress events are
trapped. I feel sure that the experts here will love to tell us both why.
 
R

RobG

Trevor & Joao:

    I re-did Trevor's testexample and now (using IE7) I can't make *any*
combination work to get the <enter> key to move forward.

The standard key for "moving forward" in nearly all modern UIs is the
tab key. The enter key normally executes the default action, which
for a form is to submit the form. I don't understand why you want to
mess with the standard UI. To guide navitation, you can use the
tabindex attribute with tab key.

Could you please copy this example to your machine, and tell me what to
change to make it work ?? [...]
<html>
<head>
<title>Enter-Key Problem</title>
</head>

<!-- MWS Feb 1/09 Now, *nothing* works. Even if I use
   the onKeyDown event, I still go right to 'Submit'
   Can someone take this code and make it work Please ?? -->

<body onload="forms.frmregister.firstname.focus();">

The forms property belongs to the document object, so:

<form id="frmregister" method="POST">

The action attribute is mandatory, but likely irrelevant here.

<input type="text" id="firstname" value="Trevor"

To be successful, form controls must have a name attribute with a
valid value, otherwise they will not be submitted with the form. They
can also have an ID.

   onKeyPress="if(event.keyCode==13,forms.frmregister.surname.focus();">

Syntax error, try something like:

onkeypress="
if(event.keyCode == 13) {
document.forms.frmregister.surname.focus();
return false;
}
">

However I don't recommend that you do that. The user should use the
tab key.


Forget the faux XHTML.

[...]
<input type="submit" name="submit" value="LOGIN" />

Don't ever give a form control a name of "submit", it will mask the
form's submit method. As a general rule, do not give any HTML element
a name or id value that matches any DOM property name (e.g. submit,
reset, length, class, checked, etc.), especially form controls.
 
R

rf

Trevor said:
Mel,
Yes, that was what I wrote in my post which crossed with yours.

I can get it to work PROVIDED that there is no submit button. Perhaps
forms treat Enter as if it were a submit regardless of how onkeypress
events are trapped. I feel sure that the experts here will love to
tell us both why.

The event bubbles up. When it gets to the form element the form is, of
course, submitted. If this is not to occur then the bubbling must be
cancelled, which the code I have seen in this thread so far does not do.

OP: Why does your client want his web page to be the only one of billions
out there to behave this way? On every other web page that contains a form
the tab key is used to move around (including shift-tab to move back, which
you are not considering) and enter to submit the form.

That is the way web forms work, why re-invent something else that will
confuse the user?
 
M

Mel Smith

Trevor:

Thanks for the re-corected corrected code !

I'm going golfing today with my wife and another couple, but my mind
will be on your suggestions until late this afternoon. :)

-Mel Smith
 
M

Mel Smith

Rob said:

The standard key for "moving forward" in nearly all modern UIs is the
tab key. The enter key normally executes the default action, which
for a form is to submit the form. I don't understand why you want to
mess with the standard UI. To guide navitation, you can use the
tabindex attribute with tab key.


You are correct of course ! but I have had suggestions that I could
'complement' the action of <Tab> by allowing the user to <enter> to move
forward among possibly 20 or so data input fields (they are used to doing
this in older Desktop apps).


<body onload="forms.frmregister.firstname.focus();">

The forms property belongs to the document object, so:

<form id="frmregister" method="POST">

The action attribute is mandatory, but likely irrelevant here.

<input type="text" id="firstname" value="Trevor"

To be successful, form controls must have a name attribute with a
valid value, otherwise they will not be submitted with the form. They
can also have an ID.

onKeyPress="if(event.keyCode==13,forms.frmregister.surname.focus();">

Syntax error, try something like:

onkeypress="
if(event.keyCode == 13) {
document.forms.frmregister.surname.focus();
return false;
}
">

However I don't recommend that you do that. The user should use the
tab key.


Forget the faux XHTML.

[...]
<input type="submit" name="submit" value="LOGIN" />

Don't ever give a form control a name of "submit", it will mask the
form's submit method. As a general rule, do not give any HTML element
a name or id value that matches any DOM property name (e.g. submit,
reset, length, class, checked, etc.), especially form controls.



Rob:

Thanks for the valuable advice. I'm certainly going to go over this and
apply corrections and see whay transpires !

-Mel Smith (now off golfing)
Mesa, Arizona
 
M

Mel Smith

Hi to Trevor, Rob, and rf:

I changed my example (enter.htm) to get it validated, and presentable
and found (as Trevor said) that removing the submit clause allows the
<Enter> key to move focus forward.

However, if the Submit Clause is active, then <enter> causes focus to go
to 'Submit' and the doc is submitted.

This bubbling was mentioned. and I believe that there is a 'cancelbubble
function somewhere, but how is it activated within an Input Text field.

Iam showing below my latest enter.htm example with changes suggested by you
folks

(I wish I could leave this alone, but I really want to understand what is
going on, and how I can capture (later) *any* key that is entered in a text
input box -- *not just* the <Enter> key )

Thanks for your help !

-Mel Smith

****************** here is my latest effort *******************

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>Enter-Key Problem</title>

<script type="text/javascript">

function getNumber(e) {
if(window.event) //IE
return e.keyCode;
else if(e.which) //Netscape/Firefox/Opera
return e.which;
}
</script>

</head>

<body onload="document.forms.frmregister.nfirstname.focus();">

<form id="register" name="frmregister" action="post">

<input type="text" id="firstname" name="nfirstname" value="Trevor"
onkeydown="if(getNumber(event)==13)
document.forms.frmregister.nsurname.focus();" />
<br />

<input type="text" id="surname" name="nsurname" value="Lawrence"
onkeydown="if(getNumber(event)==13)document.forms.frmregister.naddress.focus();"
/>

<br />

<input type="text" id="address" name="naddress" value="123 SomeStreet"
onkeydown="if(getNumber(event)==13)document.forms.frmregister.ncity.focus();"
/>

<br />

<input type="text" id="city" name="ncity" value="City of Hope"
onkeydown="if(getNumber(event)==13)document.forms.frmregister.nstate.focus();"
/>
<br />

<input type="text" id="state" name="nstate" value="State of Despair"
onkeydown="if(getNumber(event)==13)document.forms.frmregister.nzipcode.focus();"
/>

<br />

<input type="text" id="zipcode" name="nzipcode" value="85208"
onkeydown="if(event.keyCode==13)document.forms.frmregister.nfirstname.focus();"
/>

<br />
<br />

<!-- <input type="submit" name="register" value="REGISTER" /> -->

</form>
</body>

</html>
 
R

RobG

Hi to Trevor, Rob, and rf:

    I changed my example (enter.htm) to get it validated, and presentable
and found (as Trevor said) that removing the submit clause allows the
<Enter> key to move focus forward.

And the user can't submit the form. If the listener returns false,
the default action is stopped and the form is not submitted (did you
try my example?). Of course if the user has scripting disabled, the
form will submit.
    However, if the Submit Clause is active, then <enter> causes focus to go
to 'Submit' and the doc is submitted.

You mean if you have a submit button.

Rather than try to fix that, here's something to get you started. It
is not intended to be final code, just some help along the way.
Likely elements such as radio buttons or checkboxes will have
inappropriate behaviour. Note that the tab key still works, wean the
users off the enter key and onto tab if you can.

One of the failings is that to go backward, users must use shift+tab.
Also, to get past the login button to the reset button, they must use
tab or the pointing device - enter will submit the form if the submit
button has focus.

It would be nice to be able to use the enter key on the numpad (which
used to be called "transmit" in the days of dumb terminals) to
differentiate between return and enter, but that's not popular these
days.


<title>Enter-Key Problem</title>

<script type="text/javascript">

function focusNextFormControl(el) {
var controls;
if (el && el.form) {
controls = el.form.elements;

for (var i=0, len=controls.length; i<len; i++) {
if (el == controls) {
controls[++i].focus();
}
}
}
}

function handleClick(e) {

if (!e) return;

var key = e.keyCode;

if (key == 13) {
var el = e.target || e.srcElement;

if (el.type != 'submit' && el.type != 'reset') {
focusNextFormControl(el);
return false;
}
}
}

</script>

<body onload="document.forms[0].elements[0].focus();">
<form action="" onkeypress="return handleClick(event);">
<input name="firstname" value="Trevor"><br>
<input name="surname" value="Lawrence"><br>
<input name="address" value="123 SomeStreet"><br>
<input name="city" value="City of Hope"><br>
<input name="state" value="State of Despair"><br>
<input name="zipcode" value="85208"><br>
<input type="submit" value="Login">&nbsp;<input type="reset">
</form>
</body>
 
T

Thomas 'PointedEars' Lahn

RobG said:
function focusNextFormControl(el) {
var controls;
if (el && el.form) {
controls = el.form.elements;

for (var i=0, len=controls.length; i<len; i++) {
if (el == controls) {
controls[++i].focus();
}
}
}
}


It would be less error-prone if the visibility and enabled status of the
control would be checked, and maybe if the focus() method would be
feature-tested before called.

It would be more efficient if the controls would be determined only once
(provided the form itself doesn't change). And the `tabindex' attribute
should be considered, too. JSX's dhtml.js has getElementsByTabIndex() for that.

<body onload="document.forms[0].elements[0].focus();">

An accessibility nightmare, IMHO.


PointedEars
 
M

Mel Smith

Rob:

All this morning I've tried another technique (provided to me by
Kol_Horus of another html group for beginners). I modifed this and am now
presenting a working solution

Another problem: I would like to get the Page-Up and Page-Down keys to
go to the first and last input fields. I have tried to implement this but
can't seem to get it to work. However, I have the Up-arrow and down-arrow
keys working to go up and down the text fields.

I have validated this code on the w3c website: no errors

Thanks for the guidance (and I'll look and try to understand your code later
today.

-Mel Smith
Mesa, Arizona

******************** Here's the code **********************
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>Enter-Key Problem</title>

<script type="text/javascript">
function focusOnElement(event,next,previous)
{
if(event.keyCode=='13' || event.keyCode=='40') /* Enter key and
Down-Arrow key */
{document.getElementById(next).focus();
}
if(event.keyCode=='38') /* Up-Arrow key */
{document.getElementById(previous).focus();
}
if(event.keyCode=='33') /* Page-Up key */
{document.getElementById('firstname').focus();
}
if(event.keyCode=='33') /* Page-Down key */
{document.getElementById('zipcode').focus();
}

}
</script>

</head>

<body onload="document.forms.frmregister.nfirstname.focus();">

<form id="register" name="frmregister" action="post">

<input type="text" id="firstname" name="nfirstname" value="Trevor"
onkeyup="focusOnElement(event,'surname','zipcode');" />
<br />

<input type="text" id="surname" name="nsurname" value="Lawrence"
onkeyup="focusOnElement(event,'address','firstname');" />

<br />

<input type="text" id="address" name="naddress" value="123 SomeStreet"
onkeyup="focusOnElement(event,'city','surname');" />

<br />

<input type="text" id="city" name="ncity" value="City of Hope"
onkeyup="focusOnElement(event,'state','address');" />
<br />

<input type="text" id="state" name="nstate" value="State of Despair"
onkeyup="focusOnElement(event,'zipcode','city');" />

<br />

<input type="text" id="zipcode" name="nzipcode" value="85208"
onkeyup="focusOnElement(event,'firstname','state');" />

<br />
<br />

<input type="button" name="register" value="REGISTER"
onclick="document.getElementById('register').submit()"/>

</form>
</body>

</html>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,740
Latest member
JudsonFrie

Latest Threads

Top