Search code examples
phpinputwoocommercehook-woocommerceautofocus

WooCommerce Checkout Country field to Autofocus its search input once dropdown is selected


I've just started with PHP and I want to customize a Woocommerce Checkout field relating to the Country dropdown. I have no idea where I have to access the code for this field and how I can set a listener for it.

The problem is once I open the country dropdown field, I must manually click its Search input to be able to search through the countries. I need to make this search input focused, so once the user opens the dropdown he/she can search by typing without clicking on the input.

I know this must not be enough details, since there are no code snippets here. but any help is appreciated here. Thanks.

This is the problem I have with the Search input in dropdown


Solution

  • Its an issue with select2 - https://github.com/select2/select2/issues/5993

    There is a solution to the problem. Here is one of the solutions since we have more than one select on default checkout form. Create js file where to add your js code. For the example my file will be located in mythemefolder / assets / js / select2fix.js

    In your functions.php file add this

    function theme_checkout_select2fix() {
        // I need this only on checkout page. Change this if you need to load it to different pages.
        if(is_checkout()):
            wp_enqueue_script( 'select2fix', get_template_directory_uri() . '/assets/js/select2fix.js', array('jquery'));
        endif;
    }
    add_action( 'wp_enqueue_scripts', 'theme_checkout_select2fix' );
    

    Place this in your select2fix.js file

    jQuery(function($) {
        $(document).on('select2:open', () => {
            let allFound = document.querySelectorAll('.select2-container--open .select2-search__field');
            allFound[allFound.length - 1].focus();
        });
    });