0

I want to run the following html5 geolocation javascript before submitting the form. Basically I'm after this process: the geolocation popup appears when submitting the form, the user clicks allow and then the form will be processed.

function getGeoLocation() {
    navigator.geolocation.getCurrentPosition(setGeoCookie);
}

function setGeoCookie(position) {
    var cookie_val = position.coords.latitude + "|" + position.coords.longitude;
    document.cookie = "lat_lng=" + escape(cookie_val);
}

And I'm trying to accomplish this via an onclick event from the form:

<%= form_tag search_path, :method => "get" do %>
    <%= text_field_tag :search, params[:search], autofocus: true,
                   placeholder: "Enter keyword to search" %>
    <%= submit_tag "Search", name: nil, onclick: "getGeoLocation();", :style => "display: none;" %>
<%end%>

But unfortunately nothing is happening, I'm receiving no errors under browser inspector as well! Any ideas on how to implement this?

Update 1

I'm also using autocomplete to submit the form:

$(document).ready(function() {
    $("#search").autocomplete({
        source: "/search_suggestions",
        autoFocus: true,
        select: function(event, ui) {
            $(event.target).val(ui.item.value);
            $('#search').closest("form").submit();
            return false;
        }
    });
});

If I use @Alex Kojin it redirects me to another form a have inside another tab.

2 Answers 2

1

You can easily solve this with

$('form').submit(function(e) { e.preventDefault(); });
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the reply @Obaiid Farooq!! Please check out update 1 for more info.
1

You need to bind to form's submit event, and there execute your code.

In case you use jquery:

$('form').submit(function(e) {
  e.preventDefault();
  getGeoLocation();
});

Manually submit the form in setGeoCookie method:

function setGeoCookie(position) {
    var cookie_val = position.coords.latitude + "|" + position.coords.longitude;
    document.cookie = "lat_lng=" + escape(cookie_val);

    $('form').submit();
}

6 Comments

Thanks for the reply @Alex Kojin! Can you give me a few pointers on how to do this.
Geolocation is async, though.
@Alex Kojin , The geolocation popup appears but when I hit allow, it doesn't process the form, thus it doesn't redirect to the results!
Is it call setGeoCookie method? Try to call in the end $('#search form').submit();
@Alex Kojin, if I put $('form').submit it processes another form and if I put $('#search form').submit(); it doesn't do anything! weird I know!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.