Answer the question
In order to leave comments, you need to log in
How to pass values from js to hidden_field in Ruby on Rails?
Hi I'm using Ruby on Rails 5.2 and mapbox for geocoding and I'm trying to transfer latitude and longitude values from js to hidden_field using document.getElementById
my code
<%= form_for(@place, remote: true, html: { role: 'form', multiple: true }) do |f| %>
<%= f.hidden_field :longitude, id: 'lng' %>
<%= f.hidden_field :latitude, id: 'lat' %>
<div id='map' style='height: 300px;'></div>
<script>
mapboxgl.accessToken = 'Access_Token';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11'
});
var lng;
var lat;
var lngDisplay = document.getElementById('lng');
var latDisplay = document.getElementById('lat');
var marker = new mapboxgl.Marker({
'color': '#314ccd'
});
map.on('click', function(e) {
marker.setLngLat(e.lngLat).addTo(map);
lng = e.lngLat.lng;
lat = e.lngLat.lat;
lngDisplay.textContent = lng;
latDisplay.textContent = lat;
});
</script>
<div class="form-group">
<%= f.submit 'Save', data: {disable_with: 'Save...'}, class: 'btn btn-s'%>
</div>
<% end %>
<input id="lng" type="hidden" value="" name="place[longitude]">4.928367069077325
<input id="lat" type="hidden" value="" name="place[latitude]">51.613135708889615
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question