Stop 'enter' key submitting form when using jquery ui autocomplete widget

馋奶兔 提交于 2019-12-05 02:15:26
jzm

You can use an event handler on it.

$("#searchTextBox").keypress(function(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if(code == 13) { //Enter keycode
        return false;
    }
});

see: jQuery Event Keypress: Which key was pressed?

also: http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/javascript-char-codes-key-codes.aspx for list of keycodes

$("#autocomplete_field_id").keypress(function(event){
  var keycode = (event.keyCode ? event.keyCode : event.which);
  if (keycode == '13') {
    event.preventDefault();
    event.stopPropagation();    
  }
});

One way is to handle key press and ignore it if it is the enter key.

SalutonMondo

The answer ace post helped me solve my problem. While you should notice that the code ace provide must exist before $('input').autocomplete(*****), otherwise you would not receive any effect.

If you still want the enter key to submit, after the autocomplete selection is made,

if (evt.keyCode === 13 && !$('.ui-autocomplete').is(':visible')) {
   $('.ui-button:first').click();
}
evt.stopPropagation();

You could try this:

<input id="MyTextBox" type="text" onkeydown="return (event.keyCode!=13);" />

This will disable the Enter key only on the input text box

One line of code:

$("#searchField").on('keypress', (event) => event.which !== $.ui.keyCode.ENTER);

3 things that are different here than the accepted answer:

  1. jQuery normalizes event.which, so no need to test for event.keyCode and event.which.
  2. Since you're obviously using jQuery UI, you have access to named key codes via $.ui.keyCode, which makes it more readable.
  3. The ES6 arrow function syntax further simplifies the code.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!