The simplest, understandable and uncomplicated js to implement the function of enter key tab

Keywords: IE Firefox

The simplest, understandable and uncomplicated js implementation of enter key tab function text box jump

When we beginners start to learn js form validation, they may want to use the enter key to realize the jump of text box, which is more convenient, but they will find that pressing the enter key will submit the form, which is very desperate. Here is my own research tips, feel very simple, to share with you, let's start!
First, a form is as follows

<form action="" method="post" name="myform"  "return check()">
	<table>
		<tr><td>User name:</td><td><input name="user" type="text" value=""  id="user"   "change_text(event)"/></tr>
		<tr><td>&nbsp;&nbsp;Password:</td><td><input name="psd" type="text" value=""  id="psd" "back_text(event)"/></td></tr>
	</table>
	<input name="sub"  type="submit"  value="&#8730; & nbsp; OK "/ >
</form>

To put it simply, it is verified that pressing enter will first raise the onkeypress event to execute the change_text(event) function, and then call the check() function
, so the following js code:

var text1 = 0;//The variable used to implement the text jump of the enter. If you have a little more text boxes, you can use a number to assemble var textarry = new arry (enter the number of your text boxes)
var text2 = 0;
function change_text(e)
{
	var keynum;
	if(window.event) // IE
		 {
			 keynum = e.keyCode;
		}
		else if(e.which) // Netscape/Firefox/Opera
		 {
			keynum = e.which;
		}
		if(keynum==13)
		{
			//alert("press enter");
			text1 = 1;//The text box representing user is pressed enter, so that when you jump to the check function, you will know which element of Array array to use
		}
}
			
			function back_text(e)
			{
				var keynum;
				if(window.event) // IE
				  {
				  	keynum = e.keyCode;
				  }
				else if(e.which) // Netscape/Firefox/Opera
				  {
				  	keynum = e.which;
				  }
				if(keynum==13)
					{
						//alert("press enter");
						text2=1;
						
					}
			}
			
			function check()
			{
				//alert("call commit function"); 
				
				user= document.getElementById("user");
				psd = document.getElementById("psd");
				
				if(text1==1)//enter from user text box
				{
					psd.focus();
					text1=0;//After changing the cursor, this sign should be changed back for the convenience of next time
				}
				if(text2==1)//enter from psd text box
				{
					user.focus();
					text2=0;
				}
				
				
				return false;
			}

OK, it's done in this way, but it's important to note that each time you press enter, the check() function of the form will be submitted once, so if this function has other operations (such as validation, etc.), you should pay attention to the use.

Posted by zackat on Sun, 08 Dec 2019 23:47:41 -0800