Loading image

Blogs / Programming

How to use Select2 Multi-Checkboxes using JavaScript

How to use Select2 Multi-Checkboxes using JavaScript

  • showkat ali
  • 0 Comments
  • 3865 View

 

This tutorial will show you how to use JavaScript and Select2 to create a multi-checkbox dropdown. This method allows users to select multiple alternatives from a drop-down list, making it ideal for forms that allow for more than one option.

Before we begin, make sure jQuery and Select2 are included in your challenge. If you have not already, you can download them from their respective websites.

jQuery: https://jquery.com/download/
Select2: https://select2.org/getting-started/basic-usage


Once you have jQuery and Select2, incorporate them in your HTML file.

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>

Now let us use JavaScript to create a multi-checkbox dropdown.

Creating the HTML Structure:

First, we need to create the HTML structure for the drop-down. Add the following code to your HTML file:

 

    <div class="container">
        <div class="row">
            <h4>Select2 multiselect checkbox</h4>
            <select class="js-example-basic-multiple js-states form-control w-100" multiple="multiple" name="pickup_day[]" id="multiSelect">
                <option value="monday">Monday</option>
                <option value="tuesday">Tuesday</option>
                <option value="wednesday">Wednesday</option>
                <option value="thursday">Thursday</option>
                <option value="friday">Friday</option>
                <option value="saturday">Saturday</option>
                <option value="sunday">Sunday</option>
            </select>
        </div>
    </div>

Applying Select2:

Next, we need to apply Select2 to the dropdown using JavaScript. Add the following code to your HTML file:

 

  $('.js-example-basic-multiple').select2({
    placeholder: 'Select options',
    closeOnSelect: false,
    templateResult: formatState,
    allowHtml: true,
    allowClear: true,
    tags: true
});

$('#multiSelect').on('select2:select', function(e) {
    updateCheckboxState();
});

$('#multiSelect').on('select2:unselect', function(e) {
    updateCheckboxState();
});

function updateCheckboxState() {
    var selectedOptions = $('.select2-results__option[aria-selected=true]');
    selectedOptions.each(function() {
        var $checkbox = $(this).find('.select2-checkbox');
        $checkbox.prop('checked', true);
    });

    var unselectedOptions = $('.select2-results__option[aria-selected=false]');
    unselectedOptions.each(function() {
        var $checkbox = $(this).find('.select2-checkbox');
        $checkbox.prop('checked', false);
    });
}

function formatState(state) {
    if (!state.id) {
        return state.text;
    }

    var $state = $(
        '<span><input type="checkbox" class="select2-checkbox" /> ' + state.text + '</span>'
    );

    $state.find('.select2-checkbox').prop('checked', state.selected);

    $state.find('.select2-checkbox').on('click', function() {
        state.selected = !state.selected;
        $(this).prop('checked', state.selected);
        $('#multiSelect').trigger('change');
    });

    return $state;
}
                                            

In the above code, we use the select2() function to apply Select2 to the dropdown with the class js-example-basic-multipleand use ID multiCheckboxDropdown for select and check the checkbox .

The final result will be a drop-down list where users can select multiple options. The selected options will be displayed as checkboxes.

Conclusion:

In this tutorial, we learned how to create a multi-checkbox dropdown using Select2 and JavaScript. This approach provides a user-friendly interface for selecting multiple options from a drop-down list.

 

Here are the links, for example:

1 .select2 multiselect with Checkbox   Try It

2. How add Select2 Multi Select Checkbox using javascript  Try It

 

Having trouble in Select2 with managing multiple selections? How to use Multiple Select as Count in the Select2 Search Box is covered in our most recent blog post! ★

Find out how to:
🔹 Show counts for the items you have chosen.
🔹 Manage choices with ease
🔹 Make the user experience better with clear checkboxes

👉 Read more: https://www.interviewsolutionshub.com/blog/using-multiple-select-as-count-in-the-select2-search-box

 

 

 

  • Programming
showkat ali Author

showkat ali

Greetings, I'm a passionate full-stack developer and entrepreneur based in Pakistan. I specialize in PHP, Laravel, React.js, Node.js, JavaScript, and Python. I own interviewsolutionshub.com, where I share tech tutorials, tips, and interview questions. I'm a firm believer in hard work and consistency. Welcome to interviewsolutionshub.com, your source for tech insights and career guidance

0 Comments

Post Comment

Recent Blogs

Recent posts form our Blog

How to Use Spatie Role and Permission Package in Laravel 11: A Complete Guide

How to Use Spatie Role and Permission Package in Laravel 11: A Complete Guide

showkat ali
/
Programming

Read More
Understanding Laravel's whereAny and whereAll: A Tutorial with SQL Examples

Understanding Laravel's whereAny and whereAll: A Tutorial with SQL Examples

showkat ali
/
Programming

Read More
Build and Deploy Your Laravel Application Using GitHub Actions

Build and Deploy Your Laravel Application Using GitHub Actions

showkat ali
/
Programming

Read More
how to install node js in shared hosting server

how to install node js in shared hosting server

showkat ali
/

Read More
The Difference Between === and == in JavaScript: A Complete Guide

The Difference Between === and == in JavaScript: A Complete Guide

showkat ali
/
Programming

Read More
The most confusing word pairs in English

The most confusing word pairs in English

Nasir Hussain
/
English

Read More