Reputation: 467
I have the following form:
<% category.child_categories.sort_by(&:name).each do |child_category| %>
<%= form_tag (search_path), :method => "get", class: "search-form" do %>
<label for="checkData" style="cursor: pointer;" class="search">
<%= hidden_field_tag :shop_search, child_category.id %>
<i class="fas fa-search"></i> <%= child_category.name %>
</label>
<%= submit_tag '', :style => "display: none;" %>
<% end %>
<% end %>
When I click on a label and if the cookies[:coordinates] does exist, then the form gets submitted with $(this).parent('form.search-form').trigger('submit.rails');
:
$(".search").click(function(e){
<% if cookies[:coordinates].blank? %>
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(setGeoCookie, displayError);
} else {
alert("Geolocation is not supported by the browser you are currently using. Supported browsers: Chrome 5.0, Firefox 3.5, Internet Explorer 9.0, Opera 10.60, Safari 5.0");
}
function setGeoCookie(position) {
let cookieName = "coordinates";
let now = new Date();
let time = now.getTime();
time += 3600 * 5000;
now.setTime(time);
let cookie_val = position.coords.latitude + "|" + position.coords.longitude;
document.cookie = cookieName +"=" + cookie_val + '; path=/';
$(this).parent('form.search-form').trigger('submit.rails');
}
function displayError(error) {
let errors = {
1: 'error',
2: 'Position unavailable',
3: 'Request timeout'
};
alert("Error: " + errors[error.code]);
window.location.reload(true)
}
getLocation();
<% else%>
$(this).parent('form.search-form').trigger('submit.rails');
<% end %>
});
And when the cookies[:coordinates] doesn't exist I have to create the cookie first and then trigger the form inside the function setGeoCookie
. But for some odd reason the form is not being submitted. Any ideas what I might be doing wrong?
Upvotes: 1
Views: 155
Reputation: 1124
Inside the function $(this)
has another scope. Try to store the form before executing the function. Then it sould work.
$(".search").click(function(e){
var form = $(this).parent('form.search-form')
<% if cookies[:coordinates].blank? %>
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(setGeoCookie, displayError);
} else {
alert("Geolocation is not supported by the browser you are currently using. Supported browsers: Chrome 5.0, Firefox 3.5, Internet Explorer 9.0, Opera 10.60, Safari 5.0");
}
function setGeoCookie(position) {
let cookieName = "coordinates";
let now = new Date();
let time = now.getTime();
time += 3600 * 5000;
now.setTime(time);
let cookie_val = position.coords.latitude + "|" + position.coords.longitude;
document.cookie = cookieName +"=" + cookie_val + '; path=/';
form.trigger('submit.rails');
}
function displayError(error) {
let errors = {
1: 'error',
2: 'Position unavailable',
3: 'Request timeout'
};
alert("Error: " + errors[error.code]);
window.location.reload(true)
}
getLocation();
<% else%>
form.trigger('submit.rails');
<% end %>
});
Upvotes: 1