Magento – Magento 2 How to add onKeyUp to a text field in customer checkout address form

addressjavascriptmagento2onepage-checkout

I want to add a auto complete function to the customer checkout address form, but I found that the address fields are rendered by knockout js, I can't add the "onKeyUp" attribute directly. How can I add the "onKeyUp" to the textfield in the checkout form?

Best Answer

You can do this by adding the checkout_index_index.xml layout file from the Magento_Checkout module to your theme or module with this contents:

<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="checkout" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="checkout.root">
            <arguments>
                <argument name="jsLayout" xsi:type="array">
                    <item name="components" xsi:type="array">
                        <item name="checkout" xsi:type="array">
                            <item name="children" xsi:type="array">
                                <item name="autocomplete" xsi:type="array">
                                    <item name="sortOrder" xsi:type="string">0</item>
                                    <item name="component" xsi:type="string">js/autocomplete</item>
                                </item>
                            </item>
                        </item>
                    </item>
                </argument>
            </arguments>
        </referenceBlock>
    </body>
</page>

We are adding a new js file, autocomplete.js, to the list of components that the checkout page will load.

Define autocomplete.js with contents like:

define([
    'jquery',
    'jquery/ui'
], function ($) {
    'use strict';

    $.widget('mage.checkoutAutocomplete', {
        initContainer: function () {
            $('#checkout').on('keyup', this.keyUpHandler)
        },

        keyUpHandler: function (e) {
            if (e.target.getAttribute('type') === 'text') {
                // Do something with event target
            }
        }
    });

    return $.mage.checkoutAutocomplete;
});