Search code examples
javascriptjquery-select2

How to make trigger change work in Select2?


There is a piece of code that is responsible for updating the QR code during events ['paste', 'keyup', 'change'], but for some reason the Select2 list does not work and accordingly, does not transmit data.

my part of code

let apply_reload_qr_code_event_listeners = () => {
        document.querySelectorAll('[data-reload-qr-code]').forEach(element => {
            let events = ['paste', 'keyup', 'change'];
            events.forEach(event_type => {
                element.removeEventListener(event_type, reload_qr_code_event_listener);
                element.addEventListener(event_type, reload_qr_code_event_listener);
            })
        });
    }

Even though data-reload-qr-code is added to input Select2, it does not work, but all other fields work without problems.


Solution

  • I fix it like that:

    let apply_reload_qr_code_event_listeners = () => {
    
    $('[data-reload-qr-code]').each(function () {
        let $element = $(this);
        let events = ['paste', 'keyup', 'change'];
    
        events.forEach(event_type => {
            $element.off(event_type, reload_qr_code_event_listener);
            $element.on(event_type, reload_qr_code_event_listener);
        });
    
        if ($element.is('select')) {
            if ($element.data('select2')) {
                $element.off('select2:select', reload_qr_code_event_listener);
                $element.on('select2:select', reload_qr_code_event_listener);
                reload_qr_code_event_listener({ target: blurInput });
            }
        }
    });
    };