Home > Enterprise >  Rails passing value to hidden field using javascript
Rails passing value to hidden field using javascript

Time:10-08

I have an array structured as follows:

<% @locations = [['Town 1',2],['Town 2',2]...] %>

That I pass through an options_for_select tag that passes the shows the town name correctly and passes the id when submitted which is great. But, what I want to do is pass the town name (key?) as well to display on the results page as well. I understand the best method is to use a hidden_field_tag with javascript to pass the value through, but all I can pass is the id value, not the town name value.

Form

<%= form_tag(results_path, method: :post) do %>
  <%= select_tag :location, options_for_select(@locations) %>
  <%= hidden_field_tag(:location_name, value = nil, html_options = {id: 'locationName'}) %>
  <%= submit_tag 'Submit' %>
<% end %>

Javascript

$('#location').change(function(){
  var input = document.getElementById("location");
  var site = document.getElementById("locationName");
  site.value = input.value;
})

CodePudding user response:

As you're using jquery:

$('#location').change(function(){
  var locationName = $("#location option:selected").text(); # this will return the selected option text e.g. location name
  $("#locationName").val(locationName);
})

Hope it works!

  • Related