A
A
Anton Ipatov2019-07-19 10:48:22
JavaScript
Anton Ipatov, 2019-07-19 10:48:22

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 %>

in the browser console gives:
<input id="lng" type="hidden" value="" name="place[longitude]">4.928367069077325
<input id="lat" type="hidden" value="" name="place[latitude]">51.613135708889615

And does not save the value

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Michael, 2019-07-19
@IpatovAnton

If lngDisplay is an input, then
lngDisplay.value = lng;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question