0

In magento 2 (checkout) I need to hide and show some fields.

<div class="field" data-bind="visible: visible, attr: {'name': element.dataScope}, css: additionalClasses" name="shippingAddress.custom_attributes.codice_fiscale">


<style>
.nascondi {
display:none;
}
</style>

<script type="text/javascript">
    require(['jquery'], function($){
        $(document).ready(function(){
        $('div[name="shippingAddress.custom_attributes.codice_fiscale"]').addClass('nascondi');
            alert("test di lettura jquery");
            
        });
    });
</script>

But not work. Alert function work (there is not an error) but the field div[name="shippingAddress.custom_attributes.codice_fiscale"] still visible.

Why? where is the error?

Thanks

2 Answers 2

1

Checkout in Magento Luma theme uses uicomponent and knockout technology. jquery will rarely make what you want the ui to do.. All uicomponents have paths and these are visible in the registry.

the idea is to find the input path in the registry. An example below and I put a public repository for you to get a full working example too.

toggleCompanyField: function () {
            registry.get(this.pathBillingFormFields+'.company', function(field) {
                if (field.visible()) {
                    field.hide();
                } else {
                    field.show();
                }
            });
        }

https://bitbucket.org/magstaging/company-field/src/master/

2
  • don't forget its async
    – Anton S
    Oct 9, 2020 at 12:01
  • I fix with another type of solution. thansk for your support Oct 12, 2020 at 12:34
0

The problem is that there are so many asynchronous processes happening on the Magento frontend that it can be very difficult to time a jQuery script appropriately.

In you case, your script may be executing before the target element is added to the DOM.

If you can determine what component is rendering your target element, you can write a mixin that executes your script.

Or, you can write the mixin to trigger a custom event that you script is bound to.

https://devdocs.magento.com/guides/v2.4/javascript-dev-guide/javascript/js_mixins.html

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.