Detect Enter Key press Using Javascript

Uncategorized

Hello friends, this tutorial is about to detect enter key press using javascript.

friends please follow bellow steps,

Step 1: Create an Html page and copy below code on it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<html>
    <head>
        <title>Javascript code to detect Enter Key</title> 
       <!-- Latest compiled and minified CSS -->       
       <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/
3.3.7/css/bootstrap.min.css">      
      <!-- jQuery library -->       
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/
jquery.min.js"></script>     
     <!-- Latest compiled JavaScript -->      
     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/
bootstrap.min.js"></script> 
     <style type="text/css"> 
         .container{ 
               margin-top: 50px; border:1px solid rgba(158, 158, 158, 0.49); 
               padding-bottom: 50px; 
          }
         h4{ margin-top:20px; color:gray; text-align: center; } 
     </style> 
   </head>
   <body>
             <div class="container"> 
                 <h4>Detect Enter Key press Using Javascript</h4> 
                 <div class='form-group'> 
                     <div class="col-md-4"> 
                         <label>Enter Name</label> 
                         <input type="text" name="name" id="name" class="
form-control">
                     </div> 
                </div> 
            </div>
         // Javascript code //
   </body>
</html>

Step 2: Here our javascript code to detect the enter key. Copy and paste this code on your html page.(above html code copy this script and paste it on line number 31).

1
2
3
4
5
6
7
<script type="text/javascript">
    document.getElementById('name').onkeypress = function(e) { 
        if (e.which == 13 || e.keyCode == 13) {
            alert('Pressed Key is Enter Key....');     
        } 
    }   
</script>

Step 3 : Save…Open Your browser and run the html page. Click on the input field and then press enter key.

Leave a Reply

Your email address will not be published. Required fields are marked *