I am trying to add a checkbox to the checkout page in Magento2, but I am having issues with it. I have worked through http://devdocs.Magento.com/guides/v2.0/howdoi/checkout/checkout_form.html and successfully add a checkout form with a button, which works all well and good. I am able to bind an element to a function, but I need to bind a checkbox to an observable.
Now, I have read a I need an observable because when I try to click the checkbox, it remains empty. I don't know how to do that and am looking for some assistance.
I have seen in other questions code similar to:
var viewModel = {
setInstoreShipping: ko.observable(false)
};
viewModel.setInstoreShipping.subscribe(function (newState) {
if (newState) {
alert("Checked!");
} else {
alert("Unchecked!");
}
});
ko.applyBindings(viewModel);
but when applying this, I receive an error:
You cannot apply bindings multiple times to the same element
. So my question is, how do I bind a checkbox to an observable and how do I create the observable to bind to?
Best Answer
It's because checkout page already do knockout binding when it is rendered. You need to create an UI component and work with that. Your component is defined in
checkout_index_index.xml
file, like this:Then create component js file similar to this
and then in html file