Rails 3:如何汇总多个集合选择?

时间:2012-07-02 19:57:08

标签: jquery ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1

我有一个名为“Size”的选择框集合,其值为10,25,50等。我可以使用jquery添加/删除此字段,以便例如页面上可以有3种不同的大小选择:25,50和10.如果我想在这个页面上总结这些值,并得到85的总和,我该怎么做到这一点?

audience.rb

SIZE = ['5', '10', '25', '50', '75', '100']

form.html.erb

<%= f.fields_for :audiences do |audience_form| %>
  <div class="audiencefields">
  <span class="audienceforminsert"></span>  
  <div>
    <%= audience_form.label :number_of_people, "Size" %><br />
    <%= audience_form.collection_select :number_of_people, Audience::SIZE, :to_s, :to_s, :include_blank => true %>
  </div>

  </div>

  <%= audience_form.link_to_remove "Remove this audience", :id => "removelink" %>
  <% end %>

  <p><%= f.link_to_add "Add another audience", :audiences, :id => "addlink" %></p>

的application.js

$("#removelink").hide().filter(":first-child").show();

$('form a.add_nested_fields, form a.remove_nested_fields').live('click', function(){
$("div.audiencefields span.audienceforminsert").each(function(index, element) {
    //index starts with 0
    $(this).text("Audience");});
});

$("span.audienceshowinsert").each(function(index, element) {
    //index starts with 0
    $(this).text("Audience " + (index + 1));
});

1 个答案:

答案 0 :(得分:0)

找到所有选择框并添加他们选择的值:

var combined = 0;
$("select").each(function() {
    combined += parseInt($(this).val());
});

以下是jsFiddle示例。