toggle_select_all_on_select_input_using_jquery

Hi all!

Today I am going to teach something very useful, as you noticed in the title of this post that we are now going to learn “Toggle select all on select in JQuery”. So what are you waiting for? Let’ start.

Table of Contents

  • Introduction to Select2 jQuery Plugin
  • Key Features of Select2 Plugin
  • The reason for “Select all” in Select2
  • The first step to go-ahead
  • Writing HTML code
  • Writing JQuery Script for “Select Toggle All”
  • Putting altogether
  • Conclusion

Introduction to Select2 JQuery Plugin

Select2 is a very popular jQuery-based replacement for select boxes. Because of its searching, remote data sets, and pagination of results facility, it is widely used and loved by the developers and designers.

Key Features of Select2 Plugin

Here are some key features of this plugin:

  • Enhancing selects with the search.
  • Enhancing selects with an easy multi-select interface.
  • Loading data from JavaScript: easily load items via AJAX and have them searchable.
  • Ability to add new items on the fly (Tagging).
  • Working with large, remote datasets: ability to partially load a dataset based on the search term.
  • Support for custom templating for the rendering of results and selections.

The reason for “Select all” in Select2

In my recent project I have used select2 plugin for make my job easy but the job become worse when my client said to me “There are many items that I want to select at once, so it is headache for me to select all of theme one by one. Do something so that I select all items at once”

Then I realized that it is a must-have option but unfortunately select2 is unable to provide this facility till now. So I created a function and call it and job done. I called it the “Toggle Select All” button. So when you’ll click on it, if none is selected, all will be selected. However, if all is selected then none will be selected. So that is all my client needed.

The first step to go-ahead

Before starting our real code we’ll need select2 plugin to install or load into our project. There two main methods to do so:

  • Using Select2 from a CDN
  • Manual installation

Using Select2 from a CDN

A CDN (content delivery network) is the fastest way to get up and running with Select2!

Select2 is hosted on both the jsDelivr and cdnjs CDNs. Simply include the following lines of code in the <head> section of your page:

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

Manual Installation

I recommend that you use a CDN method if you always need updated version for your select2. This will make it easier for you to deploy your project in different environments. However, if you want to integrate Select2 into your project manually, you can download the release of your choice from GitHub. After download copy the files from the dist directory into your project. You can include these files like this:

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

But in this tutorial, I’ll use second method because I’ll deliver these files with demo pages.

There are two more ways to include these files into your project to install through a package manager like Bower or npm but we are not going to discuss it here for the now. So let’s move next.

Writing HTML Code

Now we have reached to our main point. Here we are going to write actual code that will do the magic. First we’ll create a “select” input with some data in it. See below:

<label>Select Options : </label>
<select class="toggle_select" name="all_options[]" multiple="multiple" id="all_options" style="width: 50%;">
<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>
</select>

<button id="select_all">Toggle Select All</button>

The above code will show you a dropdown list with 05 values/records in it. There are some points to be noted. I named this input as “all_options[]” because it is a multiple selected select input, then I assign a class “toggle_select”. This name “toggle_select” is changeable, I mean to give any class name that you like but you’ll give this name to JQuery function for identification of this input field.

Next I added a button with an Id “select_all”. With the help of this button we’ll toggle the select all function. Now let’s see what is in JQuery script.

Writing JQuery Script for “Select Toggle All”

Now we are writing magic spells that will do the real magic. Look at below code first then I’ll explain it.

<script type="text/javascript">

    // Variable outside the function means that it will retain its value to 0 on first page load
    var myState      =   0; 
    
    // Function that will toogle the select all
    function toggle_select_all_values(select=''){
        if(myState==0){
            $('#'+select).select2('destroy').find('option').prop('selected', 'selected').end().select2();
            myState =   1;   
        }else{
            $('#'+select).select2('destroy').find('option').prop('selected', false).end().select2();
            myState =   0;
        }  
    }

     // Initializing the select2
      $(".toggle_select").select2();
      
      //This will actually toggle the Select All
      $('#select_all').click(function(){
        toggle_select_all_values('all_options');
      });
  </script>
  

I have explain every this in code but here is some more explanation.

First we have a variable that stores a state for select input. Initially it will be 0. Then I wrote a function called “toggle_select_all_values” with only one parameter for select input ID. This function will check “myState” state, if it is 0 then in the next line code will select all values available in SELECT input and then changed the myState state to 1. As you can see I used If — else statement so in the next few lines code will unselect all values from SELECT input and then again assign a value 0 to myState. This function ends here.

In next line I have initialiaze the select2 to activate it and then I used click event on a button having id “select_all” button and execute the function by passing SELECT input id.

Here everything is finished now you can ready to use it.

Putting altogether

Below is complete code that you can easily copy and paste and can enjoy.

NOTE : We need JQuery library for this work so I have also added it.

<!DOCTYPE HTML>
<html>
<head>
<link href="dist/css/select2.min.css" rel="stylesheet" />
<script src="jQuery/jquery-2.2.3.min.js"></script>
<script src="dist/js/select2.min.js"></script>


	<title>Toggle Select All</title>
</head>

<body>
<label>Select Options : </label>
<select class="toggle_select" name="all_options[]" multiple="multiple" id="all_options" style="width: 50%;">
<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>
</select>

<button id="select_all">Toggle Select All</button>

<script type="text/javascript">

    // Variable outside the function means that it will retain its value to 0 on first page load
    var myState      =   0; 
    
    // Function that will toogle the select all
    function toggle_select_all_values(select=''){
        if(myState==0){
            $('#'+select).select2('destroy').find('option').prop('selected', 'selected').end().select2();
            myState =   1;   
        }else{
            $('#'+select).select2('destroy').find('option').prop('selected', false).end().select2();
            myState =   0;
        }  
    }

     // Initializing the select2
      $(".toggle_select").select2();
      
      //This will actually toggle the Select All
      $('#select_all').click(function(){
        toggle_select_all_values('all_options');
      });
  </script>
  
</body>
</html>

Conclusion

In this tutorial we learnt that how can we add “Toggle Select All” feature into our site. We learnt that technique using JQuery and HTML. This will help you allot in your future project because if there are many values that a user wants to select then he will definetly demand you to add this facility.

I hope you enjoyed the tutorials. There are many other interesting tutorials in this section. However, if you are interested in MySQL, PHP then you can visit following posts:

Furthermore, if you need help on anything related to MySql, PHP, JQuery then you may contact me HERE.

Leave a Reply - I will show after approval