XF 2.3 jQuery Help

Ozzy47

Well-known member
Prior to 2.3 we have something like this:
HTML:
<xf:js>
    $(function()
    {
        $('.js-presetChange').change(function(e)
        {
            var $ctrl = $(this),
                value = $ctrl.val(),
                $form = $ctrl.closest('form');

            if (value == -1)
            {
                return;
            }

            $form.find($ctrl.data('start') || 'input[name=start]').val(value);
            $form.find($ctrl.data('end') || 'input[name=end]').val('');
            $form.submit();
        });
    });
</xf:js>

How would that be written for 2.3 (and still support 2.2)?
 
No Guarantees ... (I am not really thaat experienced with JS)

JavaScript:
((document) => {
    document.querySelectorAll('.js-presetChange').forEach(elem => {
        elem.addEventListener('change', e => {
            let value = elem.value
            let form = elem.closest('form')

            if (value == -1)
            {
                return
            }

            form.querySelector((elem.dataset.start ? elem.dataset.start + ', ' : '') + 'input[name=start]').value = value
            form.querySelector((elem.dataset.end ? elem.dataset.end + ', ' : '') + ', input[name=end]').value = ''
            form.submit()
        });
    });
})(document)
 
That seems to have worked.
Thank you very much for that. Hopefully it will help me figure it out myself next time as I have a lot of addons to update.
 
Tip: Google (or Stack Overflow) "jQuery function/method plain javascript" is your friend :)
(Probably also LLMs like ChatGPT, but I don't know for sure)

I probably wouldn't try to do to everything in plain JS / JS that is compatible with 2.2 and 2.3.
It might be (a lot) easier to just have two implementations - one for 2.2 and one for 2.3 (even in the same Add-on version), at least that's what I do.
 
Back
Top Bottom