0

I've got select box with users in Rails. Is there any simple way, how to get selected instance from that selectbox?

show.html.erb:

<select id="user_select" name="user_select" class="input-medium">
   <% @users.each do |user| %>
      <option><%= user.username %></option>
   <% end %>
</select>
<!-- button to addfriend method like on next example -->

In this time, I've got something like this on this place:

<ul id="user_list" name="user_list">
   <% @users.each do |user| %>
      <li><%= user.username %></li>
      <%= link_to "Add", addfriend_project_path(@project, :user_id => user.id) %>
   <% end %>
</ul>

And I need to get some user info from that selectbox for my method -> id will be the best.

4

1 回答 1

1

而不是这样做:

<select id="user_select" name="user_select" class="input-medium">
   <% @users.each do |user| %>
      <option><%= user.username %></option>
   <% end %>
</select>

使用select_tag来自 FormHelper 的方法:

<%= select_tag :user_select, options_for_select(@users.map{|u| [u.username, u.id]}), class: 'input-medium' %>

然后,使用 jQuery 在选择框中获取 user_id 选择:

var user_id = $('#user_select').val();
# This will alert the selected user_id every time the select_box changes:
$('#user_select').change(function(event){
  alert($(this).val());
});
于 2013-05-06T15:44:50.170 回答