Magento2 Checkout – Fix jQuery Not Working for Custom Checkbox

checkoutjavascriptjquerymagento2

I am looking to create a custom checkbox field on the checkout process that a customer can click to define if they are a business customer or a consumer.

To do so I made a module with the file SomeProcessor.php:

    <?php
namespace BusinessCheckout\CustomCheckout\Block\Checkout;

class SomeProcessor
{
    /**
     * @param \Magento\Checkout\Block\Checkout\LayoutProcessor $subject
     * @param array $jsLayout
     * @return array
     */
    public function afterProcess(
        \Magento\Checkout\Block\Checkout\LayoutProcessor $subject,
        array  $jsLayout
    ) {

        $jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']['children']
        ['shippingAddress']['children']['shipping-address-fieldset']['children']['custom_checkbox'] = [
            'component' => 'Magento_Ui/js/form/element/abstract',
            'config' => [
                'customScope' => '.custom_checkbox',
                'template' => 'ui/form/field',
                'elementTmpl' => 'ui/form/element/checkbox',
                'options' => [],
                'id' => 'custom-field'
            ],
            'dataScope' => '.custom_checkbox',
            'label' => 'Is this a business order? Business T&C\'s apply.',
            'provider' => 'checkoutProvider',
            'visible' => true,
            'validation' => [],
            'sortOrder' => 50,
            'id' => 'custom-field'
        ];


        return $jsLayout;
    }
}
?>

All good so far and the checkbox appears on the checkout page as expected.

Now I've added the following jQuery to the footer of the site:

<script type="text/javascript">

jQuery(document).ready(function() {

  jQuery('form input[name="custom_checkbox"]').attr('checked', false)
  jQuery('form input[name="company"]').prop("disabled", true);

  jQuery('form input[name="custom_checkbox"]').click(function() {

    if (jQuery(this).prop("checked") == true) {

      jQuery('form input[name="company"]').prop("disabled", false);

    } else if (jQuery(this).prop("checked") == false) {

      jQuery('form input[name="company"]').prop("disabled", true);

    }

  });

});

</script>

It seems working when I enter it directly into console but not on the site footer.

The expected functionality is to have the checkbox unchecked when the page loads and the company field disabled. Then if the user clicks the checkbox the company field becomes enabled.

Any thoughts on how I can get this working?

Best Answer

Try this:

I have updated your code from 'component' => 'Magento_Ui/js/form/element/abstract', To 'component' => 'BusinessCheckout_CustomCheckout/js/form/element/customCheckbox',.

    <?php
namespace BusinessCheckout\CustomCheckout\Block\Checkout;

class SomeProcessor
{
    /**
     * @param \Magento\Checkout\Block\Checkout\LayoutProcessor $subject
     * @param array $jsLayout
     * @return array
     */
    public function afterProcess(
        \Magento\Checkout\Block\Checkout\LayoutProcessor $subject,
        array  $jsLayout
    ) {

        $jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']['children']
        ['shippingAddress']['children']['shipping-address-fieldset']['children']['custom_checkbox'] = [
             'component' => 'BusinessCheckout_CustomCheckout/js/form/element/customCheckbox',
            'config' => [
                'customScope' => '.custom_checkbox',
                'template' => 'ui/form/field',
                'elementTmpl' => 'ui/form/element/checkbox',
                'options' => [],
                'id' => 'custom-field'
            ],
            'dataScope' => 'custom_checkbox',
            'label' => 'Is this a business order? Business T&C\'s apply.',
            'provider' => 'checkoutProvider',
            'visible' => true,
            'validation' => [],
            'sortOrder' => 50,
            'id' => 'custom-field'
        ];


        return $jsLayout;
    }
}
?>

Now create new customCheckbox.js file in this path 'BusinessCheckout/CustomCheckout/frontend/web/js/form/element/' And put tthis content in that new customCheckbox.js JS file.

 define([
    'Magento_Ui/js/form/element/abstract',
    'jquery',
    'uiRegistry'
], function (abstractComponent,jQuery,uiRegistry) {
    uiRegistry.get("checkout.steps.shipping-step.shippingAddress.shipping-address-fieldset.company", function (element) {
        element.disable();
    });
    return abstractComponent.extend({
        hasChanged: function () {
            if (this.value() == true) {
                jQuery('form input[name="company"]').prop("disabled", false);
            } else if (this.value() == false) {
                jQuery('form input[name="company"]').prop("disabled", true);
            }
            return this._super();
        }
    });
});

That hasChanged methode will call while click for check and un-check.

Please run php bin/magento cache:flush and php bin/magento setup:static-content:deploy command after the changes.