ruby on rails: how to get list of items in select box from submited forms
I have a multi select box in a form. the elements in this select box is being added/removed from javascript using DO开发者_开发百科M (e.g. http://www.digimantra.com/tutorials/add-append-remove-value-in-select-html-element-using-javascript/). I want to get all the elements in the select box inside controller when form submitted.
is there any easy way to do it?
thanks.
The list of possible choices in a select box is not preserved in the form submission, only the selected options are sent.
The only way to send the list of options in the select box at the time of submission is to add/remove hidden tags listing the choices/values.
If you're updating the select DOM element by adding option children with Javascript than you should have too much farther to go. Just have the javascript that adds or removes an option to/from the list add or remove hidden fields to/from the form.
IE:
Assuming form created by this partial:
<% from_for @user do |f| %>
<%=f.collection_select :selected_values, Values.all, :id, :name %>
<% Values.all.each do |v| %>
<%= hidden_field_tag "user[select_options][#{v.name}]", v.id %>
<% end %>
<%= link_to_function "Add Twenty option",
'$("select").insert(bottom: "<option value=\"20\">twenty</option>");
$("form").insert(bottom: "<input type="hidden\" id=\"user_select_options_twenty\"
name=\"user[select_options][twenty]\" value=\"20\">"'
%>
<%= link_to_function "Remove Twenty option",
'$("select").select(\'[value="twenty"]\').remove();
$("#user_select_options_twenty").remove()'
%>
Assuming you populate hidden values for the initial select statement on page load this upon submit, params[:user][:select_options] will contain a hash of all the select options availble. The keys in this hash are the options shown, and the values of the hash are the values of those select options.
Note: posted code is untested. It may not be right, but it should be enough to put you on the right track.
精彩评论