【问题标题】:Rails, collection_check_boxes, maximum pickedRails,collection_check_boxes,最大选择
【发布时间】:2016-08-11 09:45:42
【问题描述】:

我有一个使用 collection_check_boxes 作为输入的表单。

= f.collection_check_boxes :color_ids, group.colors, :id, :name

我想阻止用户在表单中选中超过 n 个框。

我知道如何在模型中做到这一点,我只需要视图部分。谢谢!

【问题讨论】:

    标签: html ruby-on-rails


    【解决方案1】:

    最后,我决定使用jquery。

    1 在视图中,我将最大数量放在类的末尾,如下所示:

    = f.collection_check_boxes :color_ids, group.colors, :id, :name, item_wrapper_class: "bla bla2 #{group.maximum.to_s}"
    

    2 当一个输入[type=checkbox] 被点击时,我发现有多少其他人被标记

    $(this).parent().parent().siblings().children().children(':checked').length 
    

    3 我通过以下行从步骤 1 中找到允许的最大值

    max = parseInt($(this).parent().parent().attr('class').split(' ').pop());
    

    4 我将允许的最大值与已检查的最大值进行比较,并防止检查第一个是否较小。整个代码是这样的

      $('input[type=checkbox]').on('change', function(evt) {
        var max;
        max = parseInt($(this).parent().parent().attr('class').split(' ').pop());
        if ($(this).parent().parent().siblings().children().children(':checked').length + 1 > max) {
          this.checked = false;
        }
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-22
      • 1970-01-01
      • 2015-03-06
      • 1970-01-01
      • 2012-12-24
      • 2011-02-22
      • 1970-01-01
      相关资源
      最近更新 更多