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

Alessandro Gnola
  • 175
  • 2
  • 13

2 Answers2

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/

Herve Tribouilloy
  • 7,668
  • 2
  • 13
  • 28
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

jiheison
  • 622
  • 3
  • 6