Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

firefox autocomplete 'enter' keypress on autocomplete triggering enter on textbox

I have a form with some common fields like "email". I have javascript that catches the return key (13) and submits the form, but the same effect was observed when using the defaultButton property on the host panel.

If the user is on IE and is typing his email address, then selects an item from the browser's inline autocomplete by pressing ENTER, no keypress is sent to Javascript. GOOD.

On Firefox however, the textbox receives the ENTER keypress and wants to submit the form, which is not complete.

Does anyone know how to stop this other than disabling autocomplete? I can't figure out a way to detect that the keypress is actually originating from the auto complete listbox.

I'm using asp.net and jQuery.

Edit - to clarify: Pressing enter on an item in autocomplete should NOT submit the form. The IE behavior is correct (for once!).

My event handler in itself is simply:

on key up (tried keypress too) - if(e.which == 13) submitForm();

Problem is, I don't know how to detect that the ENTER press actually came from the autocomplete control

like image 835
Kir Avatar asked Feb 24 '12 13:02

Kir


2 Answers

You could store the value of the field on key down, and then check again on key up. If more than 1 character is different in the string from one key press, it's safe to assume that an autocomplete item was selected and enter should be ignored.

The only case where this wouldn't work is when you have a field like: [email protected] and you are selecting an autocomplete item with only the final letter added, the enter key would submit the form unintentionally.

Hope that gets us started at least. I am trying to sort out a bulletproof solution as well. I will update if I find one.

EDIT

Screw above. Sorted it out. If you check for the enter key on key up, and the input field value isn't the same on both key down/up, you can assume an autocomplete item was selected.

var loginCurrentInput = '';

$('input').keydown(function(e) {

  loginCurrentInput = $(this).val();

}

$('input').keyup(function(e) {

  //if enter key pressed
  if(e.keyCode == 13) {

    //check for changed input value
    if($(this).val() != loginCurrentInput) {

      loginCurrentInput = $(this).val();
      return false;

    }

    $('#button').trigger('click');

  }

}
like image 186
Marcus Avatar answered Oct 06 '22 08:10

Marcus


On enter key press, you can check what is current element on focus:

$("*:focus")

if the element is not with outocomplete attached then you can make your form submit. take a look on: How to select an element that has focus on it with jQuery

like image 45
ncn corp Avatar answered Oct 06 '22 10:10

ncn corp