Subscribe to Hosted Field events

DocsLegacyADVANCED

Last updated: Feb 27th, 7:40am

Subscribe to advanced credit and debit card payment events using an event listener. Event listeners can help you update the UI of your form based on the state of the fields.

You can subscribe to the following events:

Event name Description
focus Triggers when a field gains focus.
blur Triggers when a field loses focus.
empty Triggers when a field transitions from having data to being empty.
notEmpty Triggers when a field transitions from being empty to having data.
cardTypeChange Triggers when the possible card type changes. Only triggered by a change in the number field.
validityChange Triggers when the validity of a field changes.
inputSubmitRequest Triggers when the payer requests submission of an input field. For example, when pressing Enter or Return on the keyboard.

1. Set up event listener

Set up an event listener using the advanced credit and debit card payments on() function. Use the event object to get information about your fields and update your UI.

    1<ContentAccordion>
    2 <AccordionRow heading="cardTypeChange Example">
    3 <p
    4 style="margin-top: 3rem;"
    5 data-testid="dcac-cfe-acc1-p0"
    6 >
    7 Here is an example of how to use <code>cardTypeChange</code> to update your CVV label and placeholder:
    8 </p>
    9 <NewCodeBlockWrapper>
    10 <NewCodeBlock
    11 className="language-javascript"
    12 children={`
    13 paypal.HostedFields.render({ /* ... */ }).then(function (hostedFieldsInstance) {
    14 var cvvLabel = document.querySelector('label[for="cvv"]'); // The label for your CVV field
    15
    16 hostedFieldsInstance.on('cardTypeChange', function (event) {
    17 // This event triggers when a change in card type is detected.
    18 // It triggers only from the number field.
    19 var cvvText;
    20
    21 if (event.cards.length === 1) {
    22 cvvText = event.cards[0].code.name;
    23 } else {
    24 cvvText = 'CVV';
    25 }
    26
    27 cvvLabel.innerHTML = cvvText;
    28
    29 hostedFieldsInstance.setAttribute({
    30 field: 'cvv',
    31 attribute: 'placeholder',
    32 value: cvvText
    33 });
    34 });
    35 });
    36 `}
    37 />
    38 </NewCodeBlockWrapper>
    39 </AccordionRow>
    40 </ContentAccordion>

    2. Get the state of your form

    Use the getState function to get the state of your form without using events.

    getState Example

    The following example uses getState to confirm that all provided fields are valid before form submission:

      1var form =document.querySelector('#my-sample-form');
      2 paypal.HostedFields.render({/* ... */}).then(function(hostedFieldsInstance){
      3 form.addEventListener('submit',function(event){
      4var state = hostedFieldsInstance.getState();
      5var formValid =Object.keys(state.fields).every(function(key){
      6return state.fields[key].isValid;
      7});
      8if(formValid){
      9// Submit hosted fields card data
      10 hostedFieldsInstance.submit();
      11}else{
      12// Let the payer know their fields are invalid
      13}
      14});
      15});

      Sample event listeners

      The following examples show how to use event listeners.

      This event triggers when a field gains focus.

        1paypal.HostedFields.render({/* ... */}).then(function(hostedFieldsInstance){
        2 hostedFieldsInstance.on('focus',function(event){
        3// Your actions on focus
        4console.log(event.emittedBy,'gained focus');
        5});
        6});

        This event triggers when a field loses focus.

          1paypal.HostedFields.render({/* ... */}).then(function(hostedFieldsInstance){
          2 hostedFieldsInstance.on('blur',function(event){
          3// Your actions on blur
          4console.log(event.emittedBy,'lost focus');
          5});
          6});

          This event triggers when a field transitions from having data to being empty.

            1paypal.HostedFields.render({/* ... */}).then(function(hostedFieldsInstance){
            2 hostedFieldsInstance.on('empty',function(event){
            3// Your actions on empty
            4console.log(event.emittedBy,'is now empty');
            5});
            6});

            This event triggers when a field transitions from being empty to having data.

              1paypal.HostedFields.render({/* ... */}).then(function(hostedFieldsInstance){
              2 hostedFieldsInstance.on('notEmpty',function(event){
              3console.log(event.emittedBy,'has data');
              4});
              5});

              This event triggers when activity within the number field has changed, so the possible card type has also changed.

                1paypal.HostedFields.render({/* ... */}).then(function(hostedFieldsInstance){
                2 hostedFieldsInstance.on('cardTypeChange',function(event){
                3if(event.cards.length===1){
                4console.log(event.cards[0].type);
                5}else{
                6console.log('Type of card not yet known');
                7}
                8});
                9});

                This event triggers when the validity of a field has changed. Validity is represented in the event object as two booleans: isValid and isPotentiallyValid.

                  1paypal.HostedFields.render({/* ... */}).then(function(hostedFieldsInstance){
                  2 hostedFieldsInstance.on('validityChange',function(event){
                  3var field = event.fields[event.emittedBy];
                  4if(field.isValid){
                  5console.log(event.emittedBy,'is fully valid');
                  6}elseif(field.isPotentiallyValid){
                  7console.log(event.emittedBy,'is potentially valid');
                  8}else{
                  9console.log(event.emittedBy,'is not valid');
                  10}
                  11});
                  12});

                  This event triggers when the payer requests submission of an input field. For example, when pressing Enter or Return on the keyboard.

                    1var hostedFields =require('braintree-web/hosted-fields');
                    2var submitButton =document.querySelector('input[type="submit"]');
                    3 paypal.HostedFields.render({/* ... */}).then(function(hostedFieldsInstance){
                    4 hostedFieldsInstance.on('inputSubmitRequest',function(){
                    5// User requested submission, e.g. by pressing Enter or equivalent
                    6 submitButton.click();
                    7});
                    8});

                    Methods

                    The following methods are supported on parent and individual card fields:

                      1render(options){Promise|void}

                      The render() method creates an instance of advanced credit and debit card payments and renders the card fields for checkout based on the mapping and styles provided by options.

                      The options object maps the HTML element to each of the advanced credit and debit card payment inputs, style, and properties.

                      The options object contains the following fields:

                      • createOrder: A callback field that returns the order-id value. The order-id is a required reference ID for each order created. The order-id also associates the payer's card details with the order created.
                      • styles: A styleOptions parameter that defines the styling applied on each of the advanced credit and debit card payments inputs.
                      • fields: A fieldOptions parameter that defines the mapping of the HTML element to the advanced credit and debit card payments inputs and their properties.
                        1isEligible(){boolean}

                        The isEligible() method checks if advanced credit and debit card payments are eligible to render based on configuration and business rules.

                          1addClass(field, classname, callback<sub>opt</sub>){Promise|void}

                          The addClass1() method adds a class to a field. Use this method to update field styles when events occur elsewhere in your checkout integration. Includes the following parameters:

                          Parameter Type Description
                          field string The field you want to add a class to. Must be a valid fieldOption.
                          classname string The class to be added.
                          callback callback This callback triggers on completion. It passes any errors that occur during the call. This returns no data if the call successfully adds the class.
                            1clear(field, callback<sub>opt</sub>){Promise|void}

                            The clear() method clears the value of a field. Includes the following parameters:

                            Parameter Type Description
                            field string The field you want to clear. Must be a valid fieldOption.
                            callback callback This callback triggers on completion. It passes any errors that occur during the call. This returns no data if the call successfully adds the class.
                              1focus(field, callback<sub>opt</sub>){void}

                              The focus() method places focus on a field. Includes the following parameters:

                              Parameter Type Description
                              field string The field you want to focus. Must be a valid fieldOption.
                              callback callback This callback triggers on completion. It passes any errors that occur during the call. This returns no data if the call successfully adds the class.
                                1getState(){object}

                                The getState() method returns an object that includes the state of all fields and possible card types.

                                  1on(event, handler){void}

                                  The on() method subscribes a handler function to a named event. Events include:

                                  • blur
                                  • focus
                                  • empty
                                  • notEmpty
                                  • cardTypeChange
                                  • validityChange

                                  Events trigger a stateObject, which includes the following parameters:

                                  Parameter Type Description
                                  event string The name of the event to which you are subscribing.
                                  handler callback A callback to handle the event.
                                    1removeAttribute(options, callback<sub>opt</sub>){Promise|void}

                                    The removeAttribute() method removes a supported attribute from a field. Includes the following parameters:

                                    Parameter Type Description
                                    options object The options for the attribute you want to remove:
                                    - field: A string field from which you want to remove an attribute. Must be a valid fieldOption.
                                    - attribute: The name of the attribute you want to remove from the field.
                                    callback callback This callback triggers on completion. It passes any errors that occur during the call. This returns no data if the call successfully adds the class.
                                      1setAttribute(options, callback<sub>opt</sub>){Promise|void}

                                      The setAttribute() method sets an attribute of a field. Supported attributes are aria-invalid, aria-required, disabled, and placeholder. Includes the following parameters:

                                      Parameter Type Description
                                      options object The options for the attribute you want to set.
                                      - field: A string field from which you want to add an attribute. Must be a valid fieldOption.
                                      - attribute: The name of the attribute you want to add to the field.
                                      - value: The value for the attribute.
                                      callback callback This callback triggers on completion. It passes any errors that occur during the call. This returns no data if the call successfully adds the class.
                                        1removeClass(field, classname, callback<sub>opt</sub>){Promise|void}

                                        The removeClass() method removes a class from a field. Use this class to update field styles when events occur elsewhere in your checkout integration. Includes the following parameters:

                                        Parameter Type Description
                                        field string The field you want to remove a class from. Must be a valid fieldOption.
                                        classname string The class you want to remove.
                                        callback callback This callback triggers on completion. It passes any errors that occur during the call. This returns no data if the call successfully adds the class.
                                          1setMessage(options){void}

                                          The setMessage() method sets a visually hidden message for screen readers on a field.

                                          Includes the following options parameter, which contains the following:

                                          • field: A string field from which you want to add an attribute. Must be a valid fieldOption.
                                          • message: The message to set.

                                          Type definitions

                                          Card field events use the following types of information:

                                          Fields used in fieldOptions object.

                                          Property Type Description
                                          selector string A CSS selector to find the container where the card fields are inserted.
                                          placeholder string Used as the placeholder attribute of the input. If the browser doesn't natively supportplaceholder, it is polyfilled.
                                          type string The type attribute of the input. For example, to mask CVV input use type: "password".
                                          formatInput boolean Allow or deny automatic formatting on this field. Default is true.
                                          maskInput object or boolean Allow or deny input masking when input is not focused. If set to true, instead of an object, the defaults for the maskInput parameters are used. Default is false. The object properties are:
                                          character: A string field which specifies the character to use when masking the input. The default character ('•') uses a Unicode symbol, so the web page must support UTF-8 characters when using the default.
                                          showLastFour: A Boolean field applicable only for the credit card field. Defines whether to show the last 4 digits of the card when masking. Default is false.
                                          maxCardLength number This option only applies to the number field. Limits the card number length, even if the card brand supports longer card numbers. If the value that is passed is greater than the max length for a card brand, the smaller of the two values is used. For example, if maxCardLength is set to 16, but an American Express card, which has a max card length of 15, is entered, the max card length is 15.
                                          maxlength number This option applies only to the cvv field. Used as the maxlength attribute of the input if it is less than the default. The maxlength option is most often used to limit the length of the CVV input for CVV-only verifications when the card type is known, and to limit the length of the postal code input when cards are coming from a known region.
                                          minlength number This option applies only to the cvv field. Used as the minlength attribute of the input. The default value is 3. The minlength attribute applies only to integrations capturing a CVV without a number field.
                                          prefill string A value to be used to pre-fill the field. For example, when creating an update card form, you can pre-fill the expiration date fields with the old expiration date.
                                          rejectUnsupportedCards boolean Allow only card types that your merchant account can process. Unsupported card types invalidate the card form. For example, if you only process Visa cards, a payer entering an American Express card would get an invalid card field. This can be used only for the number field. The default is false.

                                          An object that has field objects for each field. Used in render method.

                                          Property Type Description
                                          number object field A field for card number.
                                          expirationDate object field A field for expiration date in MM/YYYY or MM/YY format.
                                          cvv object field A field for a 3 or 4 digit card verification code, such as CVV or CID.

                                          An object that represents CSS that is applied in each card field. This object looks similar to CSS, and changes font styles such as font-family or color.

                                          You can also pass the name of a class on your site that contains the styles you want to apply. The style properties are automatically pulled from the class and applied to the card field inputs

                                          .

                                          Note: Using styleOptions is recommended only for input elements. If you use a select style for the expiration date, unexpected styling might occur.

                                          cardSecurityCode

                                          Information about the security code for a card.

                                          Property Type Description
                                          name string The name of security code for card. Valid values are CVV, CID, and CVC.
                                          size number The expected length of the security code, which is most often 3 or 4.

                                          Information about the card type, sent in stateObjects.

                                          Property Type Description
                                          type string The code-friendly card type. Valid values are:
                                          american-express
                                          diners-club
                                          discover
                                          jcb
                                          maestro
                                          master-card
                                          unionpay
                                          visa
                                          niceType string The human-readable card type. Valid values:
                                          American Express
                                          Diners Club
                                          Discover
                                          JCB
                                          Maestro
                                          MasterCard
                                          UnionPay
                                          Visa
                                          code object cardSecurityCode Contains data about the card brand's security code requirements. For example, on a Visa card, the CVV is 3 digits, while on an American Express card, the CID is 4 digits.

                                          Fields data for advanced credit and debit card payments is sent in stateObjects.

                                          Property Type Description
                                          container HTML element The container DOM element on your page associated with the current event.
                                          isFocused boolean Whether the input is currently focused.
                                          isEmpty boolean Whether the user has entered a value in the input.
                                          isPotentiallyValid boolean Whether the current input could potentially be valid. For example, if a payer is entering a card number and types "41", the field recognizes that the input can become a valid entry. However, if the payer enters "4x" it is clear that the card number can't become valid. The value is true if the entry can become valid, and false if it can't.
                                          isValid boolean Whether the input is valid and can be submitted.

                                          The event payload is sent from on or getState.

                                          Property Type Description
                                          cards array Returns an array of potential cards. If the card type has been determined, the array contains only one card. Advanced credit and debit card payments use credit-card-type, an open-source card detection library.
                                          emittedBy string The name of the field associated with an event. This is not included if returned by getState. Valid values are "number", "cvv", and "expirationDate".
                                          fields object hostedFieldsFieldData Contains data about the field in the context of the event. Valid values are "number", "cvv", and "expirationDate".

                                          If you accept cookies, we’ll use them to improve and customize your experience and enable our partners to show you personalized PayPal ads when you visit other sites. Manage cookies and learn more