【问题标题】:set limit in selection for sumo dropdown设置相扑下拉选择的限制
【发布时间】:2015-10-13 09:28:56
【问题描述】:

我已经使用这个 jquery 插件SumoSelect 进行下拉选择与复选框

<select multiple="multiple" class="SlectBox" name="cat_ids[]">
    <option value="op1">Options1</option>
    <option value="op2">Options2</option>
    <option value="op3">Options3</option>
    <option value="op4">Options4</option>
    <option value="op5">Options5</option>  
</select>

此下拉菜单适用于复选框选择。 但是我想通过这个选择对不同的用户设置一些限制。

我尝试了下面的 jquery 代码,但它不能正常工作

jQuery(document).ready(function($){

var last_valid_selection = null;
  $('.SlectBox').change(function(event) {
    if ($(this).val().length > 2) {
      alert('You can only choose 2!');
      $(this).val(last_valid_selection);
    } else {
      last_valid_selection = $(this).val();
    }
  });  });

【问题讨论】:

    标签: javascript jquery html drop-down-menu sumoselect.js


    【解决方案1】:

    您可以在插件初始化时使用相扑方法unSelectAllselectItem 以及triggerChangeCombined 选项。

    参考:http://hemantnegi.github.io/jquery.sumoselect/

    在更改事件中,如果提高了限制,您可以取消全选并通过每个元素的索引设置最后一个有效选择。

    代码:

    $('#island').SumoSelect({ triggerChangeCombined: true, placeholder: "TestPlaceholder" });
    
    var last_valid_selection = null;
    $('#island').change(function (event) {
        if ($(this).val().length > 2) {
            alert('You can only choose 2!');
            var $this = $(this);
            $this[0].sumo.unSelectAll();
            $.each(last_valid_selection, function (i, e) {
                $this[0].sumo.selectItem($this.find('option[value="' + e + '"]').index());
            });
        } else {
            last_valid_selection = $(this).val();
        }
    });
    

    演示:http://jsfiddle.net/IrvinDominin/80xLm01g/

    【讨论】:

    • 它工作,但是当调用“$this[0].sumo.unSelectAll();”还为我记录错误“无法读取 null 的属性‘长度’”。还找不到在哪里。我认为它在 sumo.js 中
    【解决方案2】:

    有更好的样本。

    别忘了 triggerChangeCombined: true

        var last_selection = null;
        var load_selection = false;
        $('#SeasonIdList').change(function (event) {
            if (load_selection == true) {
                return false;
            }
    
            if ($(this).val() != null && $(this).val().length > 3) {
                load_selection = true;
                var $this = $(this);
    
                $this[0].sumo.unSelectAll();
    
                $.each(last_selection, function (i, e) {
                    $this[0].sumo.selectItem($this.find('option[value="' + e + '"]').index());
                });
    
                load_selection = false;
            } else {
                last_selection = $(this).val();
            }
        });
    

    【讨论】:

      猜你喜欢
      • 2021-08-10
      • 2018-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-02
      • 1970-01-01
      相关资源
      最近更新 更多