How to use Select2.js – jQuery replacement

How to use Select2.js – jQuery replacement

Use Cases of Select2.js

  • Enhancing native selects with search
  • Enhancing native selects with a better multi-select interface
  • Loading data from JavaScript: easily
  • Customized select drop-down box in html form.
  • Also provides many utilities like dynamic data, infinite scrolling, tagging and remote data sets etc. of results.

Installation

Select2.js is based on jQuery, so we also need to include jQuery in the project. So include this jQuery CDN.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

If you are using bower component tool, then create a new bower.json file and add the bellow code in it.

"dependencies": {
"select2": "~4.0"
}

And then run command bower install and it will be downloaded. Main select2 file is located at bellow folder. So include these files in the project.

<link href="vendor/select2/dist/css/select2.min.css" rel="stylesheet" />
<script src="vendor/select2/dist/js/select2.min.js"></script>

Alternatively you can also use bellow CDN file without downloading, just include these lines in the project.

<link href="https://cdn.jsdelivr.net/npm/select2@4.0.12/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.12/dist/js/select2.min.js"></script>

Usage

To use select2 js,

<select class=”select2″ name=”city”>
         <option value=”jaipur”>Jaipur</option>
         <option value=”bhilwara”>Bhilwara</option>
</select>

And put bellow jQuery code just before end of the </body> tag

<script type=”text/javascript”> $(document).ready(function()
{
     $(‘.select2’).select2();
});
</script>
 

For multiselect dropdown, use multiple attribute to <select> tag

<select class=”select2″ name=”city” multiple=”multiple”>
         <option value=”jaipur”>Jaipur</option>
         <option value=”bhilwara”>Bhilwara</option>
</select>

Js will be same as above.

Select2 can also load data from local array.

var data = [
     {
         id: 0,
         text: ‘Jaipur’
     },
    {
         id: 1,
         text: ‘Bhilwara’
    },
   {
         id: 2,
         text: ‘Chittorgarh’
    }
];
$(“.select2”).select2({ data: data });

Sometimes you want to load default options for all of Select2 in your web application. Then you can set default Global values by calling $.fn.select2.defaults.set(“key”, “value”);

$.fn.select2.defaults.set("theme", "classic");

You can reset default values by calling:

$.fn.select2.defaults.reset();

About us

Do you believe that your brand needs help from a creative team? Contact us to start working for your project!

Read More
 
 
 
 

     Useful Resources


 

Let's Talk

Start Cooperation with Protovo