fbpx

Tutorial

Elementor Change Standard Selects to Select2

Uses Plugins

Elementor Free
Code Snippets

Description

Long dropdowns (Selects) can be annoying. There is a JavaScript library that turns standard HTML Selects into filterable Selects, which is a much better user experience.

E.g. if you have a Select with a list of Countries, you don’t want to have to scroll through them all to find one.

This tutorial walks through some simple code, showing you how to do this with any Select field

1

PHP Code to get the required JavaScript & CSS files

The first thing you need to do is load the "Select2" libraries. Full details here.

If you have a Child Theme, you could paste the PHP code below into your functions.php file.

My preference is to use the "Code Snippets" WordPress plugin.  See here. I have also exported a JSON file which you can download below and import into your "Code Snippets".

OK. you should now be loading the required libraries.

2

HTML Widget with JavaScript and CSS

On a page with "Select Elements" that you want to be "Select2", add an HTML Widget somewhere after the content with the "Select" elements.

Copy the Javascript and CSS below and paste them into the HTML Widget.

On line 5 of the JavaScript, edit the selectors to include the elements you want to affect. If there are multiple Elements, separate them with commas. 

In the video example, the "Selector" includes any "Select" within a container/wrapper with the class "make-select2" and a Select on an Elementor Form Field.

Note: If you have an Elementor Form Widget with a Select field where you have set the ID to "form_select", add " .form-field-form_select". Elementor prepends".form-field-" to the ID you set on the field. 

 

Code (click to copy)

CSS (css)

.select2-container--default .select2-selection--single{
    padding: 10px;
    height: unset;
    color: var( --e-global-color-text );
    border-style: solid;
    border-width: 0px 0px 1px 0px;
    border-color: var( --e-global-color-text );
    border-radius: 0px 0px 0px 0px;
}

JavaScript (javascript)

;(w => {
    w.addEventListener('DOMContentLoaded', ()=>{
        const $ = jQuery;
        const selector = '.make-select2 select, #form-field-form_select';

        $(selector).select2();
    });

})(window);

PHP (php)

/* Enqueue Select2 libraries */
add_action('wp_enqueue_scripts', function(){
     wp_enqueue_style('wpg-select2', '//cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css');
     wp_enqueue_script('wpg-select2', '//cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js',['jquery']);
});

Downloads

Note: Depending on your Browser, JSON files may open in your Browser when clicked. To save the JSON, Right-click the “download” link, click “save link as”.

DescriptionAction
Code Snippet JSON - Load Select2 Libraries