在JavaScript中输入按键事件

本文翻译自:Enter key press event in JavaScript

I have a form with two text boxes, one select drop down and one radio button . 我有一个带有两个文本框的form ,一个选择下拉菜单和一个单选按钮 When the enter key is pressed, I want to call a Javascript function (User defined), but when I press it, the form is submitted. 当按下Enter键时,我想调用Javascript函数(用户定义),但是当我按下它时,将提交表单。

How do I prevent the form from being submitted when the enter key is pressed? 按下Enter键后,如何防止提交form


#1楼

参考:https://stackoom.com/question/3nUM/在JavaScript中输入按键事件


#2楼

If you're using jQuery: 如果您使用的是jQuery:

$('input[type=text]').on('keydown', function(e) {
    if (e.which == 13) {
        e.preventDefault();
    }
});

#3楼

A jQuery solution. jQuery解决方案。

I came here looking for a way to delay the form submission until after the blur event on the text input had been fired. 我来这里是为了寻找一种方法来延迟表单提交,直到触发文本输入中的模糊事件为止。

$(selector).keyup(function(e){
  /*
   * Delay the enter key form submit till after the hidden
   * input is updated.
   */

  // No need to do anything if it's not the enter key
  // Also only e.which is needed as this is the jQuery event object.
  if (e.which !== 13) {
       return;
  }

  // Prevent form submit
  e.preventDefault();

  // Trigger the blur event.
  this.blur();

  // Submit the form.
  $(e.target).closest('form').submit();
});

Would be nice to get a more general version that fired all the delayed events rather than just the form submit. 得到一个能触发所有延迟事件而不只是表单提交的更通用的版本将是很好的。


#4楼

A much simpler and effective way from my perspective should be : 在我看来,一种更简单有效的方法应该是:

function onPress_ENTER()
{
        var keyPressed = event.keyCode || event.which;

        //if ENTER is pressed
        if(keyPressed==13)
        {
            alert('enter pressed');
            keyPressed=null;
        }
        else
        {
            return false;
        }
}

#5楼

Detect Enter key pressed on whole document: 在整个文档上按检测回车键:

$(document).keypress(function (e) {
    if (e.which == 13) {
        alert('enter key is pressed');
    }
});

http://jsfiddle.net/umerqureshi/dcjsa08n/3/ http://jsfiddle.net/umerqureshi/dcjsa08n/3/


#6楼

A react js solution React JS解决方案

 handleChange: function(e) {
    if (e.key == 'Enter') {
      console.log('test');
    }


 <div>
    <Input type="text"
       ref = "input"
       placeholder="hiya"
       onKeyPress={this.handleChange}
    />
 </div>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值