Capturing ENTER key pressed (key event) for a text box

i have 2 text boxes on the form and one button. If the user hits ENTER in text box 1, i want to take the user to text box 2. If user hits ENTER in text box 2 i want to exeute the function that has been specified for the button.

Button function is validating the 2 text boxes, if ok, submits the form.

Detecting the key has some cross browser details to consider.

1)You need to add on onkeydown event handler to your textboxes.

2)Then, you have to take some steps to account for the different browsers, as well as how you added the onkeydown event to your code: inline in the tag or by assigning a function to the onkeydown event in the <head> tag:

window.onload=initialize;
function initialize()
{
   document.getElementById("textbox1").onkeydown = doSomething; //no parentheses
}

(See 4 below for further implications of how you add onkeydown to your code.)

See here:

http://www.quirksmode.org/js/events_access.html

One key point: for Netscape and W3C compatible browsers, the browser automatically sends the event as a parameter to the function assigned to onkeydown, where in IE the event is accessible within the function through window.event, so no parameter to the function is needed.

3)After you have all that squared away, you need to check which key was pressed. All the keys have numeric codes. Look at the far left hand column(decimal) here:

where you will find that the carriage return is represented by 13.

  1. If you add the onkeydown event handler by ‘registering’ it, whereby you assign it a function in the <head> tag, you can call the same function for both your textboxes(otherwise each textboxes’ onkeydown handler will need to call a different function). The function will know which textbox called the function when you use the ‘this’ keyword. So, you can have an if-statement that performs one task if this==document.getElementById(“textbox1”) and another if your second textbox called the function. If the first textbox called the function, set the focus() on the second textbox:

document.getElementById(“textbox2”).focus();

If your second textbox called the function, then:

my_other_function();

following is the form code that has 2 text boxes and one button:
<table border=“0” cellpadding=“0” cellspacing=“0” style=“border-collapse: collapse” bordercolor=“#111111” width=“710” height=“370”>
<form name=“frmTest” action=“” meyhod=“POST”>
<tr>
<td width=“100%”><input language=“javascript” onKeyUp=“HandleEvent(this, event)” type=“text” name=“T1” size=“20”></td>
</tr>
<tr>
<td width="100%"><input language=“javascript” onKeyUp=“HandleEvent(this, event)” type=“text” name=“T2” size=“20”></td>
</tr>
<tr>
<td width=“100%”>
<img border=“0” src=“images/btnSubmit.gif” width=“12” height=“16”></td>
</tr>
</form>
</table>

Following is the javascript code

function HandleEvent(t,e){
if (!e) var e = window.event;

[color=red]//T1 text box has key up event
if(t == document.getElementById(“T1”)){
var code;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;

alert(code);
}[/color]
[color=blue]//T2 text box has the keu up event
else if(t == document.getElementById(“T2”)){
var code;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;

alert(code);
}[/color]
}

IE is giving the right codes, while in Netscape both of these if else statement are false. t is not becomming equal to document.getElementById(“text Box Name”). What am i doing wrong here?

Instead of passing this onKeyUp event, i can pass a number 1 for test box 1 and 2 for text box 2 and like this i can check but this is not professional at all. Guys i am stuck and need your help.

changed the function as follows and it is working in both IE and Netscape

function HandleEvent(t,e){
if (!e) var e = window.event;

if(t.name == “T1”){
var code;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;

if(code == 13)
t.form.T2.focus();
}
else if(t.name == “T2”){
var code;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;

alert(code);
}
}

I have one question, when i change my image tag to

<input type=“image” src=“myimage.gif”>

then i hit enter in either of the text boxes the page is refreshed (i dont have action= specified in the form tag). I dont want the page to be refreshed until i have the text box 1 value and text box 2 value. In this case the function HandleEvent(t,e) is not being called.

The following is the same function as above but is well written. Thanks to help from Zyloch, www.experts-exchange.com:

function ValidateForm(){
var strMessage = new String(“”);
var objT1 = document.getElementById(“T1”);
var objT2 = document.getElementById(“T2”);
if(objT1.value == ‘’)
strMessage += "- T1 value missing
";

if(objT2.value == ‘’)
strMessage += "- T2 value missing
";

if(strMessage != ‘’)
alert(“Following problem(s) found:

" + strMessage + "
Please fix the problem(s) and try again.”)

else
window.document.forms.frmTest.submit();
}

function HandleEvent(t,e) {
//var key=(window.event)?window.event.keyCode:e.which;
if (!e) var e = window.event;
var key;
if (e.keyCode) key = e.keyCode;
else if (e.which) key = e.which;

//key = 13 is carriage return
if (key == 13) {
//only force focus to text box 2 if text box 1 is not empty
if (t.name == “T1” && t.value != ‘’){
t.form.T2.focus();
return false;
}
else if (t.name == “T2” && t.value != ‘’)
ValidateForm(); //t.form.submit();
}
}

It looks like you almost have it. Note: when you post code, use code tags or php tags. On this forum it is very easy: highlight your code, and click on one of the icons ‘php’ or ‘#’ above the textbox you type in. For quoting text, click on the icon on the far right–it’s a cartoon bubble.

The code in red is the same:


function HandleEvent(t,e)
{
	if (!e) var e = window.event;

	if(t.name == "T1")
	{
		[COLOR=DarkRed]var code;
		if (e.keyCode) code = e.keyCode;
		else if (e.which) code = e.which;[/COLOR]
		

		if(code == 13)t.form.T2.focus();
	}
	else if(t.name == "T2")
	{
		[COLOR=DarkRed]var code;
		if (e.keyCode) code = e.keyCode;
		else if (e.which) code = e.which;[/COLOR]
		alert(code);
	}
}

It will get executed no matter which branch of the if-statement is traversed. Whenever you write duplicate lines of code, you need to ask yourself why you are doing that. There are a couple of solutions: 1) you can put the code in a function and call the function, or 2) In this case, you can move those lines above the if-statement since you want them executed no matter what:

function HandleEvent(t,e)
{
	if (!e) var e = window.event;

	[COLOR=DarkRed]var code;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;[/COLOR]

	if(t.name == "T1")
	{
		if(code == 13)t.form.T2.focus();
	}
	else if(t.name == "T2")
	{		
		alert(code);
	}
}

In some cases, when you hit the carriage return, the default action is to submit the form, so I tried cancelling the action by returning ‘false’ from the function when code==13. I can get the following script to work in IE by not Firefox1.0:


<!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"
  xml:lang="en" lang="en">

<head>
<script language="javascript">
<!-- Hide from browsers lacking javascript

//Executes initialze() when the page loads--only then do
//the html elements exist--allowing you to refer to them.
window.onload=initialize;

//assign functions to each element's events('registration'):
function initialize()
{	
	//One way to access form elements:
	document.frmTest.T1.onkeydown = HandleEvent;

	//or this works too:
	document.getElementById("T2").onkeydown = HandleEvent;
}

function HandleEvent(e)
	   //Netscape browsers send 'e' automatically.
{	   //You don't care about 'e' in IE unless you include your
	   //event handler 'inline'(=in the tag), then for IE you
	   //need to pass the 'event' as an argument in your
	   //event handler and it will be in 'e'.
	   //(I'm not sure why this last part is so--the global
	   //variable window.event is supposed to hold
	   //the last event that fired, so it seems like you
	   //should be able to refer to it in the function without
	   //having to pass it as an argument)
					
	if(!e) var e = window.event;
			//For IE, when event handler is not inline. When
			//inline, pass 'event' as an argument in your
			//event handler, and 'e' will contain the event
			//already--making this line unnecessary.

	if (e.keyCode)
	{
		code = e.keyCode;
	}
	else if (e.which)
	{
		code = e.which;
	}
	
	if(code==13) //then carriage return was pressed
	{
		if(this==document.frmTest.T1)
		{    //Because of the way
		     //the function was assigned to the onkeydown
			 //events('registration'), 'this' refers to the
			 //textbox whose onkeydown event fired.
			
			document.frmTest.T2.focus();
		}
		else
		{
			another_function();
		}

		
		return false; //In some cases, hitting return is a default
					  //for submitting the form. Returning false
					  //cancels default submit on carriage return.
	}
}

function another_function()
{
	alert("function for textbox2 executed");
}

// End hiding -->
</script>

</head>


<body>

<table>
<form name="frmTest" action="" method="POST">
<tr>
<td width="100%"><input language="javascript" type="text" name="T1" size="20"></td>
</tr>
<tr>
<td width="100%"><input language="javascript"  type="text" name="T2" size="20"></td>
</tr>
<tr>
<td width="100%">
<input name="submit_button" type="submit" value="Submit" />
</tr>
</form>
</table>

</body>
</html>

Got it to work in Firefox1.0, too:

1)I changed the event to onkeypress.

2)I changed:

document.getElementById(“T2”).onkeydown = HandleEvent;

to:

document.frmTest.T2.onkeydown = HandleEvent;

I have no idea why I had to make that second change, but the keypresses weren’t being captured when I used the first line. For some reason, in Firefox1.0:

document.getElementById(“T2”) == document.frmTest.T2

is false.

3)In both Firefox 1.0 or IE6, it makes no difference in my script if you replace this html:

<input name=“submit_button” type=“submit” value=“Submit” />

with this:

<input type=“image” src=“my_image.jpg”>

Figured out why I had to change 2: there is no ‘id’ attribute in the html tags.

Thank you.