首页 > 解决方案 > 使用Rails Simple Form gem时如何通过JS onclick更改输入字段值

问题描述

我在我的 Rails 应用程序中设置了一个 JS 函数,用于获取用户的当前位置。我希望通过单击按钮将返回的坐标输入到我的 Rails 简单表单中的字段中。我尝试使用innerHTMLandvalue来更改元素,但这不适用于简单的表单 gem。任何想法让他的工作?

这是JS代码:

var x = document.getElementById("coordinates");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
    x.value = position.coords.latitude + 
    ", " + position.coords.longitude;
}

还有我的简单表单视图:

<button onclick="getLocation()">Current location</button>
<input id="coordinates"></input>

<%= simple_form_for @order do |f| %>

<%= f.input :start_point, input_html: { id: 'coordinates' } %>
<%= f.input :restaurant_location %>
<%= f.input :customer_location %>
<%= f.input :fee %>
<%= f.button :submit %>

<% end %>

标签: javascriptruby-on-railsrubygeolocationsimple-form

解决方案


推荐阅读