Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've got a form that uses the jquery autocomplete UI plugin, http://jqueryui.com/demos/autocomplete/, which all works sweet except when you press the enter key to select an item in the autocomplete list, it submits the form.

I'm using this in a .NET webforms site, so there may be javascript handling associated with the form that .NET is injecting that is overriding the jQuery stuff (I'm speculating here).

like image 835
Mick Byrne Avatar asked Aug 30 '11 00:08

Mick Byrne


6 Answers

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

like image 88
mnsr Avatar answered Oct 13 '22 12:10

mnsr


$("#autocomplete_field_id").keypress(function(event){
  var keycode = (event.keyCode ? event.keyCode : event.which);
  if (keycode == '13') {
    event.preventDefault();
    event.stopPropagation();    
  }
});
like image 39
ace Avatar answered Oct 13 '22 13:10

ace


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

like image 43
Johnie Karr Avatar answered Oct 13 '22 12:10

Johnie Karr


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

like image 33
Sandman Avatar answered Oct 13 '22 11:10

Sandman


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.

like image 40
SalutonMondo Avatar answered Oct 13 '22 13:10

SalutonMondo


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();
like image 24
Xs10tial Avatar answered Oct 13 '22 11:10

Xs10tial