如何使用Rails 4使用JQuery查找select_tag的值

时间:2014-01-28 03:55:50

标签: jquery ruby-on-rails ruby-on-rails-4

我想使用JQuery在Rails 4中找到select_tag的值。一旦我有了值,我想用部分包含单选按钮来更新视图。

我的代码无效。你能让我知道我做错了什么。

index.html.erb文件

<%= form_tag experts_path, method: :get do %>
    <p>
      <%= text_field_tag :query, params[:query] %>
    <hr>

    <h3>Skills Categories</h3>
        <%= select_tag "skill_categories", options_from_collection_for_select(@skill_categories, "id", "category"), prompt: "All Skills" %>

    <div class="skills"></div>
<% end %>

<script>
$( "#skill_categories" ).change(function() {
    var category_from_select = $(".skills").find(":selected").text();
    $(".skills").replaceWith("<div class='skills'><%=j render 'experts/skills', selected_category: category_from_select %></div>");
});
</script>

_skills / html.erb partial

<h4>Skills</h4>
<% skill_all.each do |skill| %>
    <%= radio_button_tag "skills[]", "#{skill.name}",
                         ((params[:skills] != nil) && (params[:skills].index(skill.name) != nil) ? true : false) %>
    <%= skill.name %>
<% end %>

experts_controller.erb

  def skills_search
    @skills = Skill.all
  end

experts_helper.erb

module ExpertsHelper

  def skill_all
    @skills = Skill.all
  end
end

1 个答案:

答案 0 :(得分:0)

尝试改变:

var category_from_select = $(".skills").find(":selected").text();

为:

var category_from_select = $(this).find(":selected").text();

要获得选定的选项,您需要select元素与#skill_categoriesdiv.skills