1,105,399 Community Members

convert enter key into tab key for form

Member Avatar
SchemeStarter
Newbie Poster
2 posts since Oct 2008
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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

Member Avatar
Taywin
Posting Maven
2,632 posts since Apr 2010
Reputation Points: 134 [?]
Q&As Helped to Solve: 378 [?]
Skill Endorsements: 17 [?]
 
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);
  ...
}
You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: