Use Connection Field Value In Javascript

Hello all,
I pieced together the code below (with some assistance from CHAT GPT) to be able to use the value of a connection field in Javascript. There may be a more efficient way to do it but this works for my use case and I thought I would share it.

Make sure to change the component ID.

PullConnectiionField-MadewithClipchamp-ezgif.com-video-to-gif-converter

TB.render('component_12', function() {
    function handleTitleChange(newTitle) {
        console.log('Title changed to:', newTitle);
    }
    
    // Select the element to observe
    const targetElement = document.querySelector('.select2-selection__rendered');
    
    if (targetElement) {
        // Create a MutationObserver to observe changes to the attributes
        const observer = new MutationObserver(mutations => {
            mutations.forEach(mutation => {
                if (mutation.attributeName === 'title') {
                    // Get the new title value
                    const newTitle = targetElement.getAttribute('title');
                    handleTitleChange(newTitle);
                }
            });
        });
    
        // Configuration for the observer
        const config = { attributes: true };
    
        // Start observing the target element
        observer.observe(targetElement, config);
    } else {
        console.error('Element not found');
    }
});