1

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?

1 Answer 1

0

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;
});
3
  • It works, but a js error appears: collection.js:53 Uncaught TypeError: elem.initContainer is not a function
    – Ricky.C
    Aug 5, 2016 at 1:21
  • One more problem, after refresh the page, the js does not work.
    – Ricky.C
    Aug 5, 2016 at 2:48
  • You can get rid of that error message by renaming _create to initContainer, I updated my answer to reflect this. I'm not having that problem with refreshing. There are no other errors? Aug 5, 2016 at 3:18

Your Answer

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

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