Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Autocomplete - enter to select

Tags:

autocomplete

I have Google Autocomplete set up for a text field of an HTML form, and it's working perfectly.

However, when the list of suggestions appear, and you use the arrows to scroll and select using enter, it submits the form, though there are still boxes to fill in. If you click to select a suggestion it works fine, but pressing enter submits.

How can I control this? How can I stop enter from submitting the form, and instead be the selection of a suggestion from autocomplete?

Thanks! {S}

like image 539
kinkersnick Avatar asked Jul 09 '12 01:07

kinkersnick


People also ask

How do I use Google autocomplete?

Click Search features from the menu on the left and then click the Autocomplete tab. Click on the slider to set Enable autocomplete to On. It can take up to 2-4 days for autocompletions tailored to your search engine to start appearing.


2 Answers

You can use preventDefault to stop the form being submitted when enter is hit, I used something like this:

  var input = document.getElementById('inputId');   google.maps.event.addDomListener(input, 'keydown', function(event) {      if (event.keyCode === 13) {          event.preventDefault();      }   });  
like image 97
sren Avatar answered Sep 25 '22 02:09

sren


Using the Google events handling seems like the proper solution but it's not working for me. This jQuery solution is working for me:

$('#inputId').keydown(function (e) {   if (e.which == 13 && $('.pac-container:visible').length) return false; }); 

.pac-container is the div that holds the Autocomplete matches. The idea is that when the matches are visible, the Enter key will just choose the active match. But when the matches are hidden (i.e. a place has been chosen) it will submit the form.

like image 23
mmalone Avatar answered Sep 21 '22 02:09

mmalone