twitter-bootstrap Bootstrap 双列表框:如何限制选定的选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31859295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 23:02:19  来源:igfitidea点击:

Bootstrap Dual Listbox : How to Limit Selected Option

jquerycsstwitter-bootstraplistbox

提问by Dharmana

I'm using Bootstrap Dual Listboxto help user choose some option.
You can see I have add the plugin on my project. It's success. But i got a problem when try to make a limit when user choose the option.

我正在使用Bootstrap Dual Listbox来帮助用户选择一些选项。
你可以看到我在我的项目中添加了插件。这是成功。但是当用户选择选项时尝试进行限制时我遇到了问题。

Example: There are some option, like:

示例:有一些选项,例如:

  • Apple
  • Mango
  • Orange
  • Melon
  • Guava
  • 苹果
  • 芒果
  • 橘子
  • 番石榴

User must choose 3 option. You can't choose 1,2,4, or 5.

用户必须选择 3 个选项。您不能选择 1、2、4 或 5。

The problem is about to limit the option can be choose. By default, the user is not limited to choose.

问题即将限制可以选择的选项。默认情况下,用户不限于选择。

This is some of my code:

这是我的一些代码:

<script src="<?php echo $baseurl; ?>assets/js/plugins/dual/dist/jquery.bootstrap-duallistbox.js"></script>
<link href="<?php echo $baseurl; ?>assets/js/plugins/dual/dist/bootstrap-duallistbox.css" rel="stylesheet" type="text/css" media="all">

<div id="addimeiform" class="box-content form-horizontal">
    <select multiple="multiple" id="imei_multi" name="duallistbox_demo1">
        <?php
             while ($row = mysql_fetch_array($query)) {
                 echo "<option>".$row['imei']."</option>";
             }
        ?>
    </select>
</div>

<script>
    var demo1 = $('[name=duallistbox_demo1]').bootstrapDualListbox();
</script>

If you have same problem, let share here. Thanks in advanced!

如果你有同样的问题,让我们在这里分享。先谢谢了!

回答by dm4web

  1. Use event change
  2. Count the selected values
  3. If there are more than three deselect the rest
  4. Use function refresh
  1. 使用事件 change
  2. 计算选定的值
  3. 如果超过三个取消选择其余的
  4. 使用功能 refresh


demo2.on('change', function(){
    var size = demo2.find(":selected").size();
    if(size > 3){
        demo2.find(":selected").each(function(ind, sel){            
            if(ind > 2)
                $(this).prop("selected", false)
        })
        demo2.bootstrapDualListbox('refresh', true);
    }
})  

JSFIDDLE

JSFIDDLE