1

I'm using this logic: Jquery: how to trigger click event on pressing enter key to press Submit button on Enter key press.

But on a web page Enter key seems to be disabled as Enter key press isn't invoking the callback attacthed to keypress function:

var otp_fun = function (otp_sel, cmd_btn_sel) {
            $(otp_sel).css({
                'font-size': '2em',
                'color': 'red',
                'height': '3em',
                'width': '12em'

            }).attr('type', 'text').focus().keypress(function (e) {
                if (e.which == 13) {
                    e.preventDefault();

                    console.log("otp_sel len=",$(otp_sel).val().length);
                    if ($(otp_sel).val().length >= 4)
                    {
                        console.log("pressing eeee button");
                        $(cmd_btn_sel).trigger('click');

                    }
                    return false;
                }
                else
                {
                    console.log("e.which=",e.which);
                }
            });
        }

How to re-enable this Enter key?

Community
  • 1
  • 1
user5858
  • 1,082
  • 4
  • 39
  • 79

2 Answers2

0

Attach the event handler to the window or document object:

$(window).keypress(function(e) {
  if (e.which == 13) {
    e.preventDefault();

    console.log("otp_sel len=", $(otp_sel).val().length);
    if ($(otp_sel).val().length >= 4) {
      console.log("pressing eeee button");
      $(cmd_btn_sel).trigger('click');
    }
  } else {
    console.log("e.which=", e.which);
  }
});

This will allow the user to press Enter anywhere to trigger the Submit button. If you want it to only work when focused on an element, change the window to the element's selector. This code needs to be run before it can work, so don't put it in a function that isn't called immediately.

wilsonzlin
  • 2,154
  • 1
  • 12
  • 22
0
       var otp_fun = function (otp_sel, cmd_btn_sel) {
        $(otp_sel).css({
            'font-size': '2em',
            'color': 'red',
            'height': '3em',
            'width': '12em'

        }).
  attr('type', 'text').focus().keypress(function (e) {
  var key = e.which;
  if(key == 13)  //  Enter key Code 
   {
     $(cmd_btn_sel).trigger('click'); 
   }
 });