0

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;
})

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Works a treat. Appreciate the help @Emu.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.