Dharmana Dharmana - 18 days ago 24
jQuery Question

Bootstrap Dual Listbox : How to Limit Selected Option

I'm using Bootstrap Dual Listbox to help user choose some option. You can see the plugin here: http://www.jqueryscript.net/demo/Responsive-jQuery-Dual-Select-Boxes-For-Bootstrap-Bootstrap-Dual-Listbox.

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!

Answer
  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

Comments