Compatible with IE and firefox carriage return events (js and jquery)

Source: Internet
Author: User
Tags key string printable characters

Javascript-compatible IE and firefox carriage return events
Copy codeThe Code is as follows: <script language = "javascript">
Function keypress (e)
{
Var currKey = 0, e = e | event;
If (e. keyCode = 13) document. myform. submit ();
}
Document. onkeypress = keypress;
</Script> Copy codeThe Code is as follows: <script>
Document. onkeydown = function (event)
{
E = event? Event :( window. event? Window. event: null );
If (e. keyCode = 13 ){
// Execution Method
Alert ('Carriage return detected ');
}
}
</Script>

Jquery is compatible with IE and firefox carriage return events
Copy codeThe Code is as follows: $ (document). ready (function (){
$ ("Press ENTER control"). keydown (function (e ){
Var curKey = e. which;
If (curKey = 13 ){
$ ("# Press ENTER event button control"). click ();
Return false;
}
});
});

Jquery multi-browser carriage return capture event code Copy codeThe Code is as follows: $ (document). keydown (function (event ){
If (event. keyCode = 13 ){
$ ('Form'). each (function (){
// Your code to run
});
}
});

Jquery-based button default enter event (carriage return event)
Here I will introduce the default press enter event of the button. If you can use submit, you do not need to read the following code, because submit can directly press enter by default)
It is hereby declared that the code is completed through jquery. The real-column code I personally wrote can be fully implemented. It can be used as long as it is copied, but it must be imported into the jquery package. This method supports ie and Firefox. When I was doing this, I found some code on the Internet, which basically does not support Firefox. Well, I have talked a lot about it. Start code demonstration. Thank you for choosing the correct one.Copy codeThe Code is as follows: <! DOCTYPE html PUBLIC "-// W <xmlnamespace prefix =" st1 "ns =" urn: schemas-microsoft-com: office: smarttags "/> 3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> enter events supported by Firefox and IE </title>
<Script src = "jquery.1.3.2.js" type = "text/javascript" language = "javascript"> </script>
<Script type = "text/javascript">
Document. onkeydown = function (e ){
Var theEvent = window. event | e;
Var code = theEvent. keyCode | theEvent. which;
If (code = 13 ){
$ ("# But1"). click ();
}
}
$ (Document). ready (function (){
$ ("# But1"). click (function (){
Alert ("I am an enter event," + "text value:" + $ ("# text1"). val ());
})
$ ("# But2"). click (function (){
Alert ("I Am a Jquery event" + "text value:" + $ ("# text1"). val ());
})
});
</Script>

This problem has been solved. If there is a better solution, we hope to share it with you.

Today, I am using the Enter key to submit a form for Logon. My code is as follows:Copy codeThe Code is as follows: <script language = "javascript">
Function document. onkeypress ()
{
If (event. keyCode = 13) document. myloginform. submit ();
}
</Script>

When executed in Firefox, an error occurs: missing (before formal parameters

Based on the suggestions on the internet, I changed my source code again:Copy codeThe Code is as follows: <script language = "javascript">
Document. onkeypress = function ()
{
If (event. keyCode = 13) document. myloginform. submit ();
}
</Script>

The error "event is not defined" is returned.

I found it as follows ):
It consists of four parts:
Part 1: browser button events
Part 2: compatible with browsers
Part 3: code implementation and Optimization
Part 4: Summary

Part 1: browser button events

When using js to implement keyboard record, you need to pay attention to the three types of browser key events, namely, keydown, keypress, and keyup, which correspond to the onkeydown, onkeypress, and onkeyup event handles respectively. A typical key generates all three events, namely, keydown, keypress, and keyup when the key is released.

Among the three event types, keydown and keyup are relatively low, while keypress is relatively advanced. The so-called "advanced" means that when you press shift + 1, keypress parses this key event and returns a printable result "! "Character, while keydown and keyup only record the shift + 1 event. [1]

However, keypress can only be effective for some characters that can be printed out, and for function buttons, such as F1-F12, Backspace, Enter, Escape, PageUP, PageDown and arrow direction, will not generate keypress event, however, keydown and keyup events can be generated. However, in FireFox, function keys can generate keypress events.

The event objects passed to the keydown, keypress, and keyup event handles have some common attributes. If Alt, Ctrl, or Shift is pressed together with a key, this is represented by the altKey, ctrlKey, and shiftKey attributes of the event, which are common in FireFox and IE.

Part 2: compatible with browsers

Any js involving browsers should consider browser compatibility issues.
Currently, common browsers are mainly based on IE and Mozilla. Maxthon is based on the IE kernel, while FireFox and Opera are based on the Mozilla kernel.

2.1 event Initialization

First, you need to know how to initialize the event. The basic statement is as follows:

Function keyDown (){}
Document. onkeydown = keyDown;

When the browser reads this statement, the KeyDown () function is called no matter which key is pressed on the keyboard.

2.2 Implementation of FireFox and Opera

FireFox, Opera, and other programs are much more difficult to implement than IE, so we should first describe them here.

The keyDown () function has a hidden variable-General, which is represented by the letter "e.

Function keyDown (e)

Variable e indicates that a key-down event occurs. To find which key is pressed, use the which attribute:

E. which

E. which will give the index value of the key. to convert the index value to the letter or number value of the key, the static function String. fromCharCode () is used, as follows:

String. fromCharCode (e. which)

Put the preceding statement together, we can get the key that is pressed in FireFox:Copy codeThe Code is as follows: function keyDown (e ){
Var keycode = e. which;
Var realkey = String. fromCharCode (e. which );
Alert ("key code:" + keycode + "character:" + realkey );
}
Document. onkeydown = keyDown;

2.3 Implementation of IE

The program of IE does not need the e variable. Use window. event. keyCode to replace e. which: Convert the index value of the Key to the real key value. The method is similar to: String. fromCharCode (event. keyCode), the program is as follows:Copy codeThe Code is as follows: function keyDown (){
Var keycode = event. keyCode;
Var realkey = String. fromCharCode (event. keyCode );
Alert ("key code:" + keycode + "character:" + realkey );
}
Document. onkeydown = keyDown;

2.4 determine the browser type

I learned how to obtain the key event object in various browsers. There are many methods to determine the browser type, which is easy to understand, there are also some clever methods. The general method is to use the appName attribute of the navigator object. Of course, you can also use the userAgent attribute. Here, appName can be used to determine the browser type, the appName of IE and Maxthon is "Microsoft Internet Explorer", while the appName of FireFox and Opera is "Netscape". Therefore, a simple function code is as follows:Copy codeThe Code is as follows: function keyUp (e ){
If (navigator. appName = "Microsoft Internet Explorer ")
{
Var keycode = event. keyCode;
Var realkey = String. fromCharCode (event. keyCode );
} Else
{
Var keycode = e. which;
Var realkey = String. fromCharCode (e. which );
}
Alert ("key code:" + keycode + "character:" + realkey );
}
Document. onkeyup = keyUp;

The simplest method is [2]:Copy codeThe Code is as follows: function keyUp (e ){
Var currKey = 0, e = e | event;
CurrKey = e. keyCode | e. which | e. charCode;
Var keyName = String. fromCharCode (currKey );
Alert ("key code:" + currKey + "character:" + keyName );
}
Document. onkeyup = keyUp;

The above method is clever, and a simple explanation:
First, e = e | event; this code is used for compatibility with browser event object acquisition. In JavaScript, this Code indicates that if the Hidden variable e exists in FireFox or Opera, e | event returns e. If it is in IE, if the Hidden variable e does not exist, the event is returned.
Its time, currKey = e. keyCode | e. which | e. charCode; this statement is used to ensure compatibility with the key code attribute of the browser key event object (see section 3). For example, in IE, only the keyCode attribute is available, while in FireFox, the which and charCode attributes are available, opera has the keyCode and which attributes.

The above code is only compatible with the browser and obtains the keyup event object. The key code and key character are displayed in simple mode, but the problem occurs. When you press the key, the character key is in uppercase, when you press the shift key, the characters displayed are strange, so you need to optimize the code.

Part 3: code implementation and Optimization

3.1 key code and verification code for a key event

There is a lack of portability between browsers for the key code and the Verification Code. For different browsers and different case events, the storage methods of the key code and the verification code are different, the relationship between browser and key event object attributes is shown in the following table:

As shown in the table:

In IE, there is only one keyCode attribute, and its interpretation depends on the event type. For keydown, keyCode stores the key code. For keypress events, keyCode stores a key code. The which and charCode attributes are not in IE, so the which and charCode attributes are always undefined.

In FireFox, the keyCode is always 0. When the keydown/keyup time is used, charCode = 0, and which is the key code. During event keypress, the value of which and charCode is the same, and the escape code is stored.

In Opera, the values of keyCode and which are always the same. In the keydown/keyup event, they store the key code. In the keypress time, they store the key code, but charCode is not defined, always undefined.

3.2 use keydown/keyup or keypress

The first part has introduced the differences between keydown/keyup and keypress. There is a general rule. The keydown event is the most useful for function buttons, the keypress event is the most useful for printable buttons [3].

Keypress records are mainly for printable characters and some functional buttons, so keypress is the first choice. However, as mentioned in the first part, keypress in IE does not support functional buttons, therefore, the keydown/keyup event should be used for Supplement.

3.3 code implementation
The general idea is to use the keypress event object to obtain key characters, and use the keydown event to obtain function characters, such as Enter and Backspace.

The code implementation is as follows:Copy codeThe Code is as follows: <! Doctype html public "-// W3C // dtd html 4.0 Transitional // EN">
<HTML>
<HEAD> <TITLE> js key record </TITLE>
<Meta name = "Generator" CONTENT = "EditPlus">
<Meta name = "Author" CONTENT = "Yu zhenren">
<Meta name = "Keywords" CONTENT = "js key records">
<Meta name = "Description" CONTENT = "js key record">
</HEAD>
<BODY>
<Script type = "text/javascript">
Var keystring = ""; // record the key string
Function $ (s) {return document. getElementById (s )? Document. getElementById (s): s ;}
Function keypress (e)
{
Var currKey = 0, CapsLock = 0, e = e | event;
CurrKey = e. keyCode | e. which | e. charCode;
CapsLock = currKey >=65 & currKey <= 90;
Switch (currKey)
{
// Block the backspace, tabulation, carriage return, space, direction keys, and deletion keys.
Case 8: case 9: case 13: case 32: case 37: case 38: case 39: case 40: case 46: keyName = ""; break;
Default: keyName = String. fromCharCode (currKey); break;
}
Keystring + = keyName;
}
Function keydown (e)
{
Var e = e | event;
Var currKey = e. keyCode | e. which | e. charCode;
If (currKey> 7 & currKey <14) | (currKey> 31 & currKey <47 ))
{
Switch (currKey)
{
Case 8: keyName = "[Return]"; break;
Case 9: keyName = "[tabulation]"; break;
Case 13: keyName = "[Press enter]"; break;
Case 32: keyName = "[space]"; break;
Case 33: keyName = "[PageUp]"; break;
Case 34: keyName = "[PageDown]"; break;
Case 35: keyName = "[End]"; break;
Case 36: keyName = "[Home]"; break;
Case 37: keyName = "[direction key left]"; break;
Case 38: keyName = "[direction key]"; break;
Case 39: keyName = "[right arrow key]"; break;
Case 40: keyName = "[direction key]"; break;
Case 46: keyName = "[delete]"; break;
Default: keyName = ""; break;
}
Keystring + = keyName;
}
$ ("Content"). innerHTML = keystring;
}
Function keyup (e)
{
$ ("Content"). innerHTML = keystring;
}
Document. onkeypress = keypress;
Document. onkeydown = keydown;
Document. onkeyup = keyup;
</Script>
<Input type = "text"/>
<Input type = "button" value = "clear record" onclick = "$ ('content'). innerHTML ="; keystring = ";"/>
<Br/> press any key to view the keyboard response key value: <span id = "content"> </span>
</BODY>
</HTML>

Code Analysis:
$ (): Get dom by ID
Keypress (e): intercept the escape code. Because the function buttons must be obtained using keydown, these function buttons are blocked in keypress.
Keydown (e): obtains the function buttons.
Keyup (e): displays intercepted strings.

The code is basically completed! Haha

Part 4: Summary

The initial purpose of code writing is to record keys in js and return a string.

The code above is just to use js to implement basic English key records. It is powerless to record Chinese characters. The method I can think of, of course, is to use js, keydown and keyup are used to record underlying key events. Chinese Character Parsing is of course powerless. Of course, you can use DOM to directly obtain the Chinese characters in the input, but this leaves the intention of using the key event discussed in this article to implement the key record.

The code above can also be used to add clipboard and monitor deletion functions ......

According to its instructions, I modified my code:Copy codeThe Code is as follows: <script language = "javascript">
Function keypress (e)
{
Var currKey = 0, e = e | event;
If (e. keyCode = 13) document. myform. submit ();
}
Document. onkeypress = keypress;
</Script>

Successful!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.