Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid form submit when Google Maps autocomplete address select in AngularJS

In my case the google autocomplete address search working. But when I click or press enter, the form also submit. I try the event preventdefault but it's not working!

It's my directive code.

myApp.directive('googleplace', function() {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, model,event) {
            var options = {
                types: [],

            };
            scope.gPlace = new google.maps.places.Autocomplete(element[0], options);

            google.maps.event.addListener(scope.gPlace, 'place_changed', function() {
              var location = scope.gPlace.getPlace().geometry.location;
                //
                scope.$apply(function() {

                  scope.lat = location.lat();
                  scope.lng  = location.lng();

                  event.preventDefault();
                    //alert(scope.lat);

                });
            });
        }
    };
});
like image 922
jhon Avatar asked Oct 29 '25 16:10

jhon


1 Answers

var input = document.getElementById('IdWhereYouAreSearchingForLocation');
google.maps.event.addDomListener(input, 'keydown', function(e) { 
    if (e.keyCode == 13) 
    { 
        e.preventDefault(); 
    }
});

My issue resolved. Problem was that i was just writing event.preventDefault(). You must try to know that which key is pressed? if Enter key is pressed then event.PreventDefault.

like image 79
Umair Kamboh Avatar answered Oct 31 '25 12:10

Umair Kamboh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!