Capturing Enter in IE using jQuery

4

I have the following code in jQuery:

    $(document).keypress(function(e) {
        if(e.which === 13) $('.button_ok').click();
    });

When I click the enter key, it causes the user to click on the button of class button_ok .

It works in all browsers, except in Internet Explorer. Does anyone know what it can be?

    
asked by anonymous 01.09.2016 / 16:17

5 answers

4

Second this response found in So-En e.which does not work in IE .

One alternative is to use e.KeyCode and use keydown instead of keypress .

Press run and you will see that the alert will show you the message: the enter key was pressed .

document.addEventListener('keydown', function(e){
       if(e.keyCode == 13){
          alert('a tecla enter foi pressionada');
       }
    }, false);
    
01.09.2016 / 19:19
2

The problem that occurs in your code is that the which function is not supported in older versions of Internet Explorer, only from version 9 of it.

So to solve your problem, with a simple solution and cross browser capture of the enter key, you can do as follows below:

$(document).keypress(function(e){
    var keycode = e.keyCode ? e.keyCode : e.which;
    if(keycode === 13){
        $('.button_ok').click();   
    }
});

$(document).keypress(function(e){
  var keycode = e.keyCode ? e.keyCode : e.which;
  if(keycode === 13){
    $('.button_ok').click();   
  }
});

$('.button_ok').click(function() {
  alert('OK!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><inputtype="text" name="txt_input" />
<input type="button" class="button_ok" value="OK" />

    $(window).keypress(function(e){
      var keycode = e.keyCode ? e.keyCode : e.which;
      if(keycode === 13){
        $('.button_ok').click();   
      }
    });

    $('.button_ok').click(function() {
      alert('OK!');
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><inputtype="button" class="button_ok" value="OK" />
    
01.09.2016 / 16:49
2
<input type="text" value="texto do input" id="input">
<input type="button" value="click" id="click">

$('#click').on('click', function () {                    
 alert($('#input').val());
 });
 $('#input').on('keydown', function (e) {                     
     if (e.keyCode === 13) {
         $('#click').trigger('click');
     }
 });
    
01.09.2016 / 19:06
1

I use this a lot with internet explorer compatibility:

$(function() {
    $(window).on('keydown', function(event) {
        if(event.which == 13) {
            suaAcao();
            return false;
        }
    });
});
    
01.09.2016 / 20:07
0

Use e.keyCode :

$(document).keypress(function(e) {
     var code = e.keyCode || e.which; 
     if(code === 13) $('.button_ok').click();
});
    
01.09.2016 / 16:39