在相扑下拉菜单的选择中设置限制

时间:2015-10-13 09:28:56

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

我已使用此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();
    }
  });  });

2 个答案:

答案 0 :(得分:4)

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

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

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

代码:

$('#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/

答案 1 :(得分:0)

有更好的样本。

不要忘记triggerChangeCombined:是

    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();
        }
    });