1

I am trying to create buttons to either add or remove 1 item of a certain type from the shopping cart.

In my search I found some code online that works great for Chrome but appears to not work on any other browser. the Onclick function won't get fired in Firefox.

Underneath is the javascript.

<script type="text/javascript">
require([
        'jquery'
    ],
    function ($) {
        $(window).on("load", function () {
            require([
                'Magento_Checkout/js/model/cart/totals-processor/default',
                'Magento_Customer/js/customer-data',
                'Magento_Checkout/js/model/quote',
                'Magento_Checkout/js/model/shipping-rate-processor/new-address',
                'Magento_Checkout/js/model/shipping-rate-processor/customer-address',
                'Magento_Checkout/js/model/shipping-rate-registry',
                'Magento_Checkout/js/action/get-totals'
            ], function (defaultTotal, customerData, quote, defaultProcessor, customerAddressProcessor,
                         rateRegistry, getTotalsAction) {
                $(document).ready(function () {

                    $(document).on('click', 'button.remove-button,button.add-button', function (e) {
                        var $this = $(this);
                        var ctrl = ($(this).attr('id').replace('-upt', '')).replace('-dec', '');
                        var currentQty = $("#cart-" + ctrl + "-qty").val();
                        if ($this.hasClass('increaseQty-' + ctrl)) {
                            var newAdd = parseInt(currentQty) + parseInt(1);
                            $("#cart-" + ctrl + "-qty").val(newAdd);
                        } else if ($this.hasClass('decreaseQty-' + ctrl)) {
                            if (currentQty > 0) {
                                var newAdd = parseInt(currentQty) - parseInt(1);
                                $("#cart-" + ctrl + "-qty").val(newAdd);
                            }
                        }
                        var form = $('form#form-validate');
                        var url = "<?=  $block->getUrl('checkout/cart/updatePost') ?>";
                        $.ajax({
                            url: url,
                            type: "POST",
                            data: form.serialize(),
                            showLoader: true,
                            cache: false,
                            success: function (res) {
                                var parsedResponse = $.parseHTML(res);
                                var result = $(parsedResponse).find("#form-validate");
                                var sections = ['cart'];
                                $("#form-validate").replaceWith(result);
                                // The mini cart reloading
                                customerData.reload(sections, true);

                                // The totals summary block reloading
                                var deferred = $.Deferred();
                                getTotalsAction([], deferred);
                            },
                            error: function (xhr, status, error) {
                                var err = eval("(" + xhr.responseText + ")");
                                console.log(err.Message);
                            }
                        });
                        return true;
                    });
                });

            });
        });
    });
</script>

And these are the buttons.

                    <button data-bind="click: decreaseQty" type="button" value="update_qty"
                        name="update_cart_action"
                        id="<?= /** @escapeNotVerified  */ $_item->getId() ?>-dec"
                        class="remove-button decreaseQty-<?= /* @escapeNotVerified */ $_item->getId() ?>">-
                </button>
                <input id="cart-<?= /* @escapeNotVerified */$_item->getId() ?>-qty"
                       name="cart[<?= /* @escapeNotVerified */ $_item->getId() ?>][qty]"
                       data-cart-item-id="<?= /* @escapeNotVerified */ $_item->getSku() ?>"
                       type="number"
                       size="4"
                       title="<?= $block->escapeHtml(__('Qty')) ?>"
                       class="input-text qty"
                       data-validate="<?php echo $block->escapeHtml(json_encode($block->getQuantityValidators())) ?>"
                       data-role="cart-item-qty"
                       value="<?= /* @escapeNotVerified */ $block->getQty() ?>"
                       readonly />
                <button data-bind="click: increaseQty" type="button" value="update_qty"
                         name="update_cart_action"
                        id="<?= /** @escapeNotVerified */$_item->getId() ?>-upt"
                        class="add-button increaseQty-<?= /* @escapeNotVerified */$_item->getId() ?>">+
                </button>

So as I said, this all works fine and as intended in Chrome but fails to do anything in Firefox and Edge.

UPDATE

I started testing with some alerts to see where the code gets before breaking and it seems to be able to come to "sometext2" as shown below:

<script type="text/javascript">
window.alert("sometext");

require([
        'jquery'
    ],
    function ($) {

        window.alert("sometext2");

        $(window).on("load", function () {

            window.alert("sometext3");


            require([
                'Magento_Checkout/js/model/cart/totals-processor/default',
                'Magento_Customer/js/customer-data',
                'Magento_Checkout/js/model/quote',
                'Magento_Checkout/js/model/shipping-rate-processor/new-address',
                'Magento_Checkout/js/model/shipping-rate-processor/customer-address',
                'Magento_Checkout/js/model/shipping-rate-registry',
                'Magento_Checkout/js/action/get-totals'
            ], function (defaultTotal, customerData, quote, defaultProcessor, customerAddressProcessor,
                         rateRegistry, getTotalsAction) {

                window.alert("sometext4");
10
  • 1
    How come you are binding two click events per button? One with Knockout and one with jQuery.
    – Ben Crook
    Jan 22, 2020 at 9:29
  • 1
    Damn it, worth a try! Two other ideas I have are you're calling require inside require, I've never seen this before and have no idea whether that works or not but I suspect that shouldn't be the case. Another possibility is because you're using the window on load event, I've seen it where the window load will never actually finish so it may be worth removing that and seeing if it makes a difference.
    – Ben Crook
    Jan 22, 2020 at 10:47
  • 1
    Try removing the window load and adding domReady! as a dependency, that's the Require JS way of waiting until the dom is Ready before running your JS.
    – Ben Crook
    Jan 22, 2020 at 13:03
  • 1
    Welcome to Magento 2's frontend. I think the error may be around the nested require() function but it doesn't make sense why that would work in Chrome and not Firefox.
    – Ben Crook
    Jan 22, 2020 at 13:18
  • 1
    Well, thanks anyways! I'll try to find a workaround I guess Jan 22, 2020 at 13:39

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.