Search code examples
ruby-on-railsgetelementbyid

How to add document.getElementById value inside a Ruby on Rails form?


A dynamic value (foo_value) is generated inside the script tag after the page is loaded. I would like to have that value display in the form, so when a user fills out the form, everything including the dynamic value will be stored in the model.

foo_value is dynamic and can be changed until the user submits the form.

foo_value is showing up on the browser console when I check document.getElementById('foo_value').value. But it doesn't show up in the text_field.

<%= form_with(model: fooLand) do |form| %>
  <div class="field">
    <%= form.label :foo %>
    <%= form.text_field :foo, value: "", id: :foo_value %>
  </div>
  ...
<% end %>
<script>
function generateFooValue() {
    ... //code to generate foo_value
    document.getElementById('foo_value').value = foo_value;
}
</script>

Other syntax I've tried for text_field:

<%= form.text_field :foo, value:"", id: :foo_value %>

<%= form.text_field :foo, id: :foo_value %>

<%= form.text_field :foo, id: "foo_value" %>

<%= form.text_field :foo, value: :foo_value %>

Solution

  •  <body onload="myFunction()">
        <%= form_with url: '/testing', method: :get, local: true do |form| %>
          <div class="field">
            <%= form.label :foo %>
            <%= form.text_field :foo, value: "", id: :foo_value %>
          </div>
       <% end %>
     </body>
    
    
    <script>
      function myFunction() {
        document.getElementById("foo_value").value = 'x';
      }
    </script>
    

    Updated what I have tried in my rails application. It is worked for me perfectly in my browser. When I open the page, 'x' appears in the text field.