Bootstrap Dual Listbox : How to Limit Selected Opt

2019-06-13 15:26发布

问题:

I'm using Bootstrap Dual Listbox to 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.

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.

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!

回答1:

  1. Use event change
  2. Count the selected values
  3. If there are more than three deselect the rest
  4. Use function 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