Аналог .trigger() в нативном JS в miniShop2

Здравствуйте! Подскажите, пожалуйста, может кто-то знает, в чем беда. Столкнулся с такой проблемой: необходимо переписать код jQuery в нативный. Код считывает нажатие на кнопки + или -, тем самым меняет кол-во товара в корзине. Это все работает с miniShop2. Код переписал, работает все кроме того, что цена в итоговой сумме не меняется) Мое предположение, что не работает из-за строчки
$count.trigger('change');
Пробовал переписать так:


let event = new Event('change');
simularInputElement.dispatchEvent(event);
Безуспешно.

Весь код jQuery:
$(document)
    .on('click touchend', '.input-group-text', function (e) { // input-group-text - кнопки plus/minus
        e.preventDefault();
        var $container = $(this).closest('.input-group'),
            $count = $container.find('[name="count"]'),
            num = $count.val();
        if (isNaN(num) === false) { // страховочка от, например, пустого поля
            num = parseInt(num, 10);
            switch ($(this).data('count')) { // соответственно, у кнопок должен быть атрибут data-ms2-count="plus или minus"
                case 'plus':
                    num = num + 1;
                    $count.val(num);
                    break;
                case 'minus':
                    if (num <= 1) return;
                    num = num - 1;
                    $count.val(num);
                    break;
            }
        } else {
            return false;
        }
        $container.find('.cart-label-count').text(num);
        $count.trigger('change'); // инициализируем отправку на сервер.
    })
    .on('change keypress keyup', '.ms2_form [name="count"]', function() {
        if ($(this).val().match(/\D/)) {
            console.log('тут');
            console.log($(this));
            this.value = $(this).val().replace(/\D/g,''); // следим на лету, чтобы в поле были только цифры
        }
        if (parseInt($(this).val(), 10) < 1) {
            console.log('тут2');
            console.log($(this));
            this.value = 1; // следим на лету, чтобы в поле было не меньше единицы
        }
});

Код JS:
function Bs5InputCount(selector, params = {}) {
    selector.forEach(n => {
        const simularInputElement = n.closest('.input-group').querySelector('input');
        n.addEventListener('click', () => {
                //n.preventDefault();
                let num = parseInt(simularInputElement.value);
                switch (n.getAttribute('data-count')) {
                    case 'plus':
                        if (parseInt(simularInputElement.getAttribute(params.dataMax)) > num && simularInputElement.getAttribute(params.dataMax) != null) {
                            num = num + 1;
                            simularInputElement.value = num;
                        } else if (simularInputElement.getAttribute(params.dataMax) == null) {
                            num = num + 1;
                            simularInputElement.value = num;
                        }
                        break;
                    case 'minus':
                        if (parseInt(simularInputElement.getAttribute(params.dataMin)) < num && simularInputElement.getAttribute(params.dataMin) != null) {
                            num = num - 1;
                            simularInputElement.value = num;
                        } else if (simularInputElement.getAttribute(params.dataMin) == null) {
                            num = num - 1;
                            simularInputElement.value = num;
                        }
                        break;
                }
                console.log(simularInputElement);
                // document.dispatchEvent(new Event("change"));
                // simularInputElement.dispatchEvent(new Event("change"));
                // document.dispatchEvent(new Event('change'));
                // simularInputElement.dispatchEvent(new Event('change'));
                let event = new Event('change');
                simularInputElement.dispatchEvent(event);
            }
        )
        simularInputElement.addEventListener('keyup', () => {
            if (parseInt(simularInputElement.value) < parseInt(simularInputElement.getAttribute(params.dataMin))) {
                simularInputElement.value = simularInputElement.getAttribute(params.dataMin);
            } else if (parseInt(simularInputElement.value) > parseInt(simularInputElement.getAttribute(params.dataMax))) {
                simularInputElement.value = simularInputElement.getAttribute(params.dataMax);
            }
        })
    })
}

Bs5InputCount(document.querySelectorAll('[data-count]'), {
    dataMin: 'data-min',
    dataMax: 'data-max',
})

HTML:

Дмитрий
26 мая 2022, 23:11
modx.pro
938
0

Комментарии: 13

Станислав
26 мая 2022, 23:25
0
Вот пример рабочего кода, меняется классы и все будет работать!
<form method="post" class="ms2_form form-inline" role="form">
                                    <input type="hidden" name="key" value="{$product.key}"/>
                                    <div class="cart-product-quantity">
                                        <div class="quantity">
                                            <span class="minus countButton" data-ms2-count="minus"></span>
                                            <input type="text" class="qty count" value="{$product.count}" name="count" max="100">
                                            <span class="plus countButton" data-ms2-count="plus"></span>
                                        </div>
                                    </div>
                                    <button style="display:none;" type="submit" name="ms2_action" value="cart/change"></button>
                                </form>
<th class="total_cost">
                        <span class="ms2_total_cost">{$total.cost}</span>
                        {'ms2_frontend_currency' | lexicon}
                    </th>
<script>
    $('body').on('click', '.quantity .control', function (e) {
        var type = $(this).parent(),
            input = $(this).siblings('input.count'),
            count = input.val();
    
        if ($(this).hasClass('plus')) {
            count++;
        } else if ($(this).hasClass('minus') && count > 1) {
            count--;
        }
        input.val(count);
        input.change();
    });
    $(document)
    .on('click touchend', ".countButton", function (e) {
        e.preventDefault();
        var $container = $(this).closest('.ms2_form'),
        $count = $container.find('[name="count"]'),
        num = $count.val();
        if (isNaN(num) === false) {
            num = parseInt(num, 10);
            switch ($(this).data('ms2-count')) {
                case 'plus':
                    num = num + 1;
                    $count.val(num);
                    break;
                case 'minus':
                    if (num <= 1) return;
                    num = num - 1;
                    $count.val(num);
                    break;
            }
        } else {
            return false;
        }
        $count.trigger('change');
    })
    .on('change keypress keyup', '.ms2_form [name="count"]', function() {
        if ($(this).val().match(/\D/)) {
            this.value = $(this).val().replace(/\D/g,'');
        }
        if (parseInt($(this).val(), 10) < 1) {
            this.value = 1;
        }
    });
</script>
    Дмитрий
    26 мая 2022, 23:35
    0
    Станислав, спасибо, но суть задачи именно переписать на ванильный JS, без использования jQuery, я бы попробовал переписать Ваш код, но у Вас тоже есть эта функция trigger, аналог которой я все не могу найти
deleted
26 мая 2022, 23:57
+1
Попробуйте так: el.dispatchEvent(new Event('change', {'bubbles': true})))
Можно попробовать событие вешать на форму, а не на инпут
Авторизуйтесь или зарегистрируйтесь, чтобы оставлять комментарии.
13