Muhd
Muhd

Reputation: 25576

Autocomplete dropdown generates unwanted keydown event

On my website I have several input fields in a form. I want the user to be able to submit the form on any of the fields by hitting the enter key. However, this causes an issue because in Internet Explorer and Safari if the user types a few letters and an autocomplete dropdown opens and they use arrow keys and hit enter to do the autocomplete, the form will submit.

How can I change this behavior?

Also note that I have a custom function for "submitting". It is not the default submit.

Here is my jQuery code:

$('.submitButton').click( submitContactForm );

$('.column input, .submitButton').keydown(function( e ){
    if( e.keyCode == 13 ){// if 'enter' key
        $('.submitButton').click();
    }
});

Upvotes: 1

Views: 481

Answers (3)

Headshota
Headshota

Reputation: 21449

if you need to prevent form from submitting, you should call preventDefault() method on the event object in the event Handler.

element.onkeydown = function(event){
   var event = event || window.event;
   event.preventDefault();
   var code = event.keycode || event.which;

   if(code === 13){
    // Your enter behavior
   }
}

you can prevent event from bubbling up the DOM by calling event.stopPropagation();. if your autocomplete is the somewhere in your form this will help not to fire the event on the form but only on autocomplete.

Upvotes: 0

Muhd
Muhd

Reputation: 25576

I have decided to use the safeEnter jQuery plugin. Looks like it will solve this problem nicely.

Upvotes: 1

neworld
neworld

Reputation: 7793

you need add onkeydown event on dropdown of autocomplete and return false in function.

Upvotes: 0

Related Questions