Home > Web Front-end > JS Tutorial > body text

How to determine whether the Enter key is pressed in jquery

coldplay.xixi
Release: 2023-01-04 09:36:51
Original
2239 people have browsed it

How jquery determines whether the Enter key is pressed: Use the keynum method to determine, the code is [$('#textBox').keypress(function(event){var keynum = (event.keyCode ?event. keyC】.

How to determine whether the Enter key is pressed in jquery

The operating environment of this tutorial: windows7 system, jquery3.2.1 version, thinkpad t480 computer.

Recommendation:jquery video tutorial

How jquery determines whether the Enter key is pressed:

In jquery, Use the following method to determine whether Enter is pressed

$('#textBox').keypress(function(event){  
    var keynum = (event.keyCode ? event.keyCode : event.which);  
    if(keynum == '13'){  
        alert('You pressed a "Enter" key in textbox');    
    }  
});  
  
$(document).keypress(function(event){  
    var keynum = (event.keyCode ? event.keyCode : event.which);  
    if(keynum == '13'){  
        alert('You pressed a "Enter" key in somewhere');      
    }  
});
Copy after login

Note that Netscape/Firefox/Opera supports event.which to obtain the ASCII code of the key, while IE Both event.keyCode and event.which are supported.

Finally, the process of obtaining keynum can also be judged using if.

Supplement: jQuery gets Ctrl Enter Shift Enter

The keyboard event has been corrected in jQuery. When calling the function, you can pass in the event. The key code can be found through the event's which. However, when there is a combination When pressing the key, you need to pay attention.

For example, Ctrl Enter, although e.ctrlKey is used, the key code of the Enter key is not always 13.

In FireFox, judgeCtrl Enter is e.ctrlKey && e.which == 13

And in IE6, it is judged that Ctrl Enter is e.ctrlKey && e.which == 10

Example:

$(document).keypress(function(e){
        if(e.ctrlKey && e.which == 13 || e.which == 10) { 
                $("#btn").click();
        } else if (e.shiftKey && e.which==13 || e.which == 10) {
                $("#btnv").click();
        }          
 })
Copy after login

Related free learning recommendations: javascript(Video)

The above is the detailed content of How to determine whether the Enter key is pressed in jquery. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!