2

On the store view frontend, how would I be best to go about hiding/showing an element based upon an inputs value? I've been considering an attempt to extend collapsible.js, but am not sure if this is the right idea.

1 Answer 1

2

I suppose you could do it the old way with jQuery but this is what Knockout JS comes in very handy for (UI binding and refreshing), using the billing steps area as an example this is how it's done:

The template

This is where we apply to the binding, if canUseShippingAddress() returns true the div will be visible, if it returns false it will not be visible.

<div data-bind="visible: canUseShippingAddress()">
    ...
</div>

The javascript

This is where the logic is written to determine whether canUseShippingAddress() is true or false. You will need to replace the logic with the value of your input. For this you can use $('.your-selector').val() to retrieve the value of the form.

define([
    'ko',
    'underscore',
    'Magento_Ui/js/form/form',
    ...
],
function (
    ko,
    _,
    Component,
    ...
) {
    'use strict';

return Component.extend({
    canUseShippingAddress: ko.computed(function () {
        return !quote.isVirtual() && quote.shippingAddress() && quote.shippingAddress().canUseForBilling();
    }),
});

I have left out the rest of the code so it's easier to read, the full files are:

For more examples just search the codebase for data-bind="visible:.

I hope this helps.

Your Answer

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

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