2

I need to add one checkbox on checkout and call one function on checkbox change event, how can I do that?

Check this screenshot for better understanding exactly what I need.

enter image description here

2
  • Can you provide more info please, does this need to be within an existing UI component or in a custom one? How much UI component/KO do you know? If you already know how to work with both this is how - data-bind="checked: yourFunction" See knockoutjs.com/documentation/checked-binding.html
    – Ben Crook
    Mar 8, 2018 at 13:21
  • Yes, that i check but i need proper way to call this function.
    – Dhrumin
    Mar 8, 2018 at 13:27

2 Answers 2

17

Yes, i found a solution for checkbox change event.

I have added this checkbox on shipping method section so the html checkbox available on this path.

/view/frontend/web/template/checkout/shipping/custom.html


<input type="checkbox" name="custom" value="custom-fee" data-bind='checked: CheckVal'/>

Now, CheckVal function created in the knockout model file, for me it's available here,

/view/frontend/web/js/view/checkout/shipping/custom.js

And the code for checked or unchecked event is,

return Component.extend({
        defaults: {
            template: 'Namespace_Mymodule/checkout/shipping/custom'
        },
        initObservable: function () {

            this._super()
                .observe({
                    CheckVal: ko.observable(true)                        
                });

            this.CheckVal.subscribe(function (newValue) {
                if(newValue){
                    console.log('checked');
                }else{
                    console.log('Unchecked');
                }
            });

            return this;
        }
    });
2
  • I have tried your answer. The event is working fine. But the checkbox is selected by default onpageload when i use the data-bind. Do you have any idea?
    – Agnes
    May 30, 2018 at 13:07
  • 3
    Getting error ReferenceError: CheckVal is not defined
    – akgola
    Nov 5, 2018 at 13:03
1

you can use

  onCheckedChanged: function () {
            // do something
        }

in your js component

vendor/magento/module-ui/view/base/web/js/form/element/single-checkbox.js

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.