954,600 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

convert enter key into tab key for form

On a form, I want to jump to the next tabindex when pressing the 'enter' key. The script that should do the thing, should look like this (the tabindex is generated dynamically and the code is simplified):

<form id='MyForm'>
<?php
$tabindex = 1;
?>
<input class='pts' type='text' id='<?php echo $row['id']; ?>' tabindex='<?php echo $tabindex; ?>' onkeypress='convertEnterKey(this);' />
<?php
$tabindex++;
?>
</form>
<script type="text/javascript">
function convertEnterKey(obj) { 
	var k;
	if(window.event.which) {
		k = window.event.which.keyCode;
	} else {
		// needed for IE
		k = window.event.keyCode;
	}
	if (k == 13){ 
		nextTabIndex = obj.tabIndex + 1;
		for(i=0;i<document.MyForm.elements.length;i++){
			if(document.MyForm.elements(i).tabIndex==nextTabIndex){
				document.MyForm.elements(i).focus();
				break;
			}
		}
	}
} 
</script>

On the net I found there is some difference between FF and IE, but I can not find the exact explanation and/or implementation.
Could someone please help me out?
Thanks in advance!!!
Sincerely,
Steve

SchemeStarter
Newbie Poster
2 posts since Oct 2008
Reputation Points: 10
Solved Threads: 0
 

You need to attach the event to your page as well. You could attach the event at onload of body tag or you could simply run it.

function attachKeyEventToPage() {
  if (document.addEventListener) {  // anything but IE
    // passing event to function as closure
    document.addEventListener("keydown", function(e) { convertEnterKey(e) }, false);
  }
  else { // IE
    // passing event to function as closure
    document.attachEvent("onkeydown", function(e) { convertEnterKey(e) })
  }
}

function convertEnterKey(inEvent) {
  var e = inEvent;
  var keyCode;
  if (!e || (typeof(e)=="undefined")) { e = window.event; }
  // may not need parseInt, but I still like to do so :P
  keyCode = (e.keyCode) ? parseInt(e.keyCode,10) : parseInt(e.which, 10);
  ...
}
Taywin
Posting Virtuoso
1,727 posts since Apr 2010
Reputation Points: 229
Solved Threads: 239
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: