Subscribe to Hosted Field events

DocsLegacyAdvancedLast updated: April 17th 2024, @ 4:51:01 pm


Important: This JavaScript SDK documentation uses the legacy HostedFields component. If you are integrated with the CardFields component, see Card Field Events.

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 nameDescription
focusTriggers when a field gains focus.
blurTriggers when a field loses focus.
emptyTriggers when a field transitions from having data to being empty.
notEmptyTriggers when a field transitions from being empty to having data.
cardTypeChangeTriggers when the possible card type changes. Only triggered by a change in the number field.
validityChangeTriggers when the validity of a field changes.
inputSubmitRequestTriggers 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.

  <ContentAccordion>
    <AccordionRow heading="cardTypeChange Example">
  <p style={{ marginTop: "3rem" }} data-testid="dcac-cfe-acc1-p0">Here is an example of how to use <code>cardTypeChange</code> to update your CVV label and placeholder:</p>
  <NewCodeBlockWrapper>
    <NewCodeBlock
      className="language-javascript"
      children={`
  paypal.HostedFields.render(\{ /* ... */ }).then(function (hostedFieldsInstance) {
    var cvvLabel = document.querySelector('label[for="cvv"]'); // The label for your CVV field \n
    hostedFieldsInstance.on('cardTypeChange', function (event) {
      // This event triggers when a change in card type is detected.
      // It triggers only from the number field.
      var cvvText; \n
      if (event.cards.length === 1) {
        cvvText = event.cards[0].code.name;
      } else {
        cvvText = 'CVV';
      } \n
      cvvLabel.innerHTML = cvvText;
      hostedFieldsInstance.setAttribute({
        field: 'cvv',
        attribute: 'placeholder',
        value: cvvText
      });
    });
  });
      `}
    />
  </NewCodeBlockWrapper>
  </AccordionRow>
  </ContentAccordion>

2. Get the state of your form

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

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

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

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
4 console.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
4 console.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
4 console.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) {
3 console.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) {
3 if (event.cards.length === 1) {
4 console.log(event.cards[0].type);
5 } else {
6 console.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) {
3 var field = event.fields[event.emittedBy];
4
5 if (field.isValid) {
6 console.log(event.emittedBy, 'is fully valid');
7 } else if (field.isPotentiallyValid) {
8 console.log(event.emittedBy, 'is potentially valid');
9 } else {
10 console.log(event.emittedBy, 'is not valid');
11 }
12 });
13 });

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');
2 var submitButton = document.querySelector('input[type="submit"]');
3
4 paypal.HostedFields.render({ /* ... */ }).then(function (hostedFieldsInstance) {
5 hostedFieldsInstance.on('inputSubmitRequest', function () {
6 // User requested submission, e.g. by pressing Enter or equivalent
7 submitButton.click();
8 });
9 });

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:

ParameterTypeDescription
fieldstringThe field you want to add a class to. Must be a valid fieldOption.
classnamestringThe class to be added.
callbackcallbackThis 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:

ParameterTypeDescription
fieldstringThe field you want to clear. Must be a valid fieldOption.
callbackcallbackThis 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:

ParameterTypeDescription
fieldstringThe field you want to focus. Must be a valid fieldOption.
callbackcallbackThis 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:

ParameterTypeDescription
eventstringThe name of the event to which you are subscribing.
handlercallbackA 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:

ParameterTypeDescription
optionsobjectThe 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.
callbackcallbackThis 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:

ParameterTypeDescription
optionsobjectThe 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.
callbackcallbackThis 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:

ParameterTypeDescription
fieldstringThe field you want to remove a class from. Must be a valid fieldOption.
classnamestringThe class you want to remove.
callbackcallbackThis 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.

PropertyTypeDescription
selectorstringA CSS selector to find the container where the card fields are inserted.
placeholderstringUsed as the placeholder attribute of the input. If the browser doesn't natively supportplaceholder, it is polyfilled.
typestringThe type attribute of the input. For example, to mask CVV input use type: "password".
formatInputbooleanAllow or deny automatic formatting on this field. Default is true.
maskInputobject or booleanAllow 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.

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

PropertyTypeDescription
numberobject fieldA field for card number.
expirationDateobject fieldA field for expiration date in MM/YYYY or MM/YY format.
cvvobject fieldA 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.

Information about the security code for a card.

PropertyTypeDescription
namestringThe name of security code for card. Valid values are CVV, CID, and CVC.
sizenumberThe expected length of the security code, which is most often 3 or 4.

Information about the card type, sent in stateObjects.

PropertyTypeDescription
typestringThe code-friendly card type. Valid values are:
american-express
diners-club
discover
jcb
maestro
master-card
unionpay
visa
niceTypestringThe human-readable card type. Valid values:
American Express
Diners Club
Discover
JCB
Maestro
MasterCard
UnionPay
Visa
codeobject cardSecurityCodeContains 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.

PropertyTypeDescription
containerHTML elementThe container DOM element on your page associated with the current event.
isFocusedbooleanWhether the input is currently focused.
isEmptybooleanWhether the user has entered a value in the input.
isPotentiallyValidbooleanWhether 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.
isValidbooleanWhether the input is valid and can be submitted.

The event payload is sent from on or getState.

PropertyTypeDescription
cardsarrayReturns 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.
emittedBystringThe name of the field associated with an event. This is not included if returned by getState. Valid values are "number", "cvv", and "expirationDate".
fieldsobject hostedFieldsFieldDataContains data about the field in the context of the event. Valid values are "number", "cvv", and "expirationDate".