tajihiro
tajihiro

Reputation: 2443

How to change action value of form_tag onchange event select_tag in Rails

Ruby1.9.2 Rails3.2

The below code is going to generate next HTML code.

<%= form_tag :controller => "index", :action => "index" do %>
<%= select_tag(:area_id,
options_from_collection_for_select(@areas, :id, :area_name, @area_id),
 :onchange => "this.form.submit()") %>
<% end %>


<form accept-charset="UTF-8" action="/area/2" method="post">
    <select id="area_id" name="area_id" onchange="this.form.submit()">
      <option value="1">Japan</option>
      <option value="2" selected="selected">Thailand</option>
      <option value="3">USA</option>
      <option value="4">Canada</option>
      <option value="5">England</option>
    </select>
</form>

When I change the select box, onchange event happens. But form action value does not change "/area/2" as it is. If I select /area/1, it does not change.

I would like to know how I change the value of action, when onchange event happen.

Upvotes: 0

Views: 1523

Answers (1)

agmcleod
agmcleod

Reputation: 13621

This can be done by putting some javascript code in one of your js files in the app/assets/javascripts directory. After removing the onchange option in your select_tag call, this should take care of it:

$(function() {
  $('#area_id').change(function() {
    $(this).parent().attr('action', '/area/' + $(this).val());
  });
});

So long as your view or layout loads the application file via the javascript_include_tag method, you should be good to go.

Though instead of having the form submit on the change event, i'd recommend just adding a button, in case someone mis-selects the value they want, they dont have to hit the back button or whathave you.

Upvotes: 1

Related Questions