How to resolve a bug in the Japanese IME for tagging

I believe this issue has been resolved with the following JavaScript code, so I would like to share it with you.

jQuery(document).ready(function ($) {
    applySelect2(); // Execute on page load

    // Reapply when the page is reloaded via Ajax
    $(document).on('ajaxComplete', function () {
        applySelect2(); // Reapply after Ajax completes
    });

    function applySelect2() {
        $('.hp-field--tags').select2({
            language: "ja", // Japanese localization
            tokenSeparators: [',', ' '] // Separate by comma or space
        });

        // Fix for IME issue when entering Japanese text
        $('.hp-field--tags').on('select2:open', function () {
            let select2Field = document.querySelector('.select2-search__field');
            if (select2Field) {
                select2Field.addEventListener('compositionstart', function (e) {
                    e.stopPropagation();
                });

                select2Field.addEventListener('compositionend', function () {
                    let inputValue = select2Field.value.trim();
                    if (inputValue.length > 0) {
                        let $select = $('.hp-field--tags');
                        let newOption = new Option(inputValue, inputValue, true, true);
                        $select.append(newOption).trigger('change');
                        select2Field.value = ''; // Clear the input field
                    }
                });
            }
        });
    }
});

jQuery(document).ready(function ($) {
    $('.hp-field--tags').select2({
        language: "ja",
        tokenSeparators: [',', ' '],
        ajax: {
            url: ajaxurl, // WordPress Ajax endpoint
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    action: 'get_listing_tags', // Call the corresponding handler in functions.php
                    q: params.term // User input
                };
            },
            processResults: function (data) {
                return { results: data };
            },
            cache: true
        },
        minimumInputLength: 1
    });
});

Hi,

Thank you for your solution, it will be useful for our community.

1 Like