Multiple select by chosen

Multiple select by chosen

2,172

Probably you all know select2 which is jQuery replacement for select boxes. Select2 has awesome functionality and design, personally like it very much however since Bootstrap 4.1.x became popular select2 start showing issues specially in styling.

Select2 developers and others tried hard to make it update with new bootstrap but due to lots of complains and questions about fixing this issues select2 so far wasn't able to fix the issue, they even provided special styles for supporting bootstrap 4 but I didn't finding it handy so I was looking for alternative solution till I found CHOSEN.

Chosen is similar with select2 but I think it has more interested options, however it comes with it's own style which isn't bad at all (we get into it in the following).


Overview

Chosen is jQuery library (package) for multiple select-boxes "just like select2".

Chosen has it's own styling (which is different with bootstrap "form-control" class)

Chosen can be find here

Full document can be find here


Working with chosen

You have to download chosen first and import css & js files into your view (chosen website link provided above)

After importing files into your page we will need to provide class for our select-box (we use documentation default class chosen-select)

Sample

<select data-placeholder="Select a Roles" class="chosen-select form-control" name="roles[]" multiple>
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
  <option value="4">Four</option>
  <option value="5">Five</option>
  <option value="6">Six</option>
  <option value="7">Seven</option>
</select>
HTML

 

//importing stylesheet
<link rel="stylesheet" href="{{asset('css/chosen.min.css')}}">

//importing js file
<script src="{{ asset('js/chosen.jquery.min.js') }}" defer></script>


//script
<script>
    $(document).ready(function() {
        $(".chosen-select").chosen();
    });
</script>
JavaScript

and that's all you need to work with chosen (simple isn't it?).

Another sample

Just before I publish this article I published another one "How to limit multiple select options" which I was talking about limiting user ability of selecting options in JavaScript. The good news is chosen has this option with it so we don't have to write extra functions for it. Take a look at sample below:

<script>
    $(document).ready(function() {
        $(".chosen-select").chosen({max_selected_options: 3});
    });
</script>
JavaScript

max_selected_options is obvious name for the job it's doing, will limit user of choosing more than provided number of options. In this case user is only able to select 3 options and no more. (for more options read chosen documentation)

- Last updated 5 years ago

Ads

Be the first to leave a comment.

You must login to leave a comment