重新启用在文本字段上按Enter键

时间:2016-04-26 07:59:42

标签: jquery

我使用此逻辑:Jquery: how to trigger click event on pressing enter key提交按钮按键。

但是在web page Enter 键上似乎被禁用,因为回车键按下并不是要调用到keypress功能的回调:

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);
                }
            });
        }

如何重新启用此回车键?

2 个答案:

答案 0 :(得分:0)

将事件处理程序附加到windowdocument对象:

$(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);
  }
});

这将允许用户在任何地方按 Enter 来触发提交按钮。如果您希望它仅在关注元素时起作用,请将window更改为元素的选择器。 此代码需要先运行才能运行,因此请不要将其置于不立即调用的函数中。

答案 1 :(得分: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'); 
   }
 }); 
相关问题