【问题标题】:Rails 3: How to sum multiple collection selections?Rails 3:如何汇总多个集合选择?
【发布时间】:2012-07-03 06:13:19
【问题描述】:

我有一个名为“Size”的选择框集合,其值为 10、25、50 等。我可以使用 jquery 添加/删除此字段,例如,页面上可能有 3 种不同的尺寸选择: 25, 50, and 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));
});

【问题讨论】:

  • 你能粘贴一些代码吗?

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


【解决方案1】:

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

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

这是一个例子jsFiddle

【讨论】:

    猜你喜欢
    • 2016-12-08
    • 1970-01-01
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 2017-06-28
    • 1970-01-01
    相关资源
    最近更新 更多