选择多选选项限制最多2

Pra*_*tre 3 html javascript multi-select

我正在使用multiselect用于不同的主题我想要将select最多限制为2,并且如果用户取消选择,则以相同的方式禁用其他选项.再次,该选项必须对用户可用.

<select multiple="multiple" class="subjects" name="subjects[]" style="float:left;width:205px;" size="5">
  <option value='1'>subject1</option>
  <option value='2'>subject2</option>
  <option value='3'>subject3</option>
  <option value='3'>subject3</option>
</select>
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经实现了取消选择仅在2之后选择的最后一个选项,代码如下

    /**
     * Make sure the subject's limit is 2
     */
    $(".subjects option").click(function(e){

        if ($(this).parent().val().length > 2) {
            $(this).removeAttr("selected");
        }
    });
Run Code Online (Sandbox Code Playgroud)

谢谢.

小智 5

改进了jQuery示例,注意(else enable)选项,这修复了以前禁用select选项的示例的bug.同时删除了"请仅选择两个选项".可能时出现错误消息. http://jsfiddle.net/c9CkG/25/

jQuery(document).ready(function () {

jQuery("select").on("change", function(){
  var msg = $("#msg");

  var count = 0;

  for (var i = 0; i < this.options.length; i++)
  {
    var option = this.options[i];

    option.selected ? count++ : null;

    if (count > 2)
    {
        option.selected = false;
        option.disabled = true;
        msg.html("Please select only two options.");
    }else{
        option.disabled = false;
        msg.html("");
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

});