Events

You can subscribe to Hosted Fields events using an event listener. This allows you to update the UI of your form based on the state of the fields. These events include:

Event nameDescription
focusEmitted when a field gains focus.
blurEmitted when a field loses focus.
emptyEmitted when a field transitions from having data to being empty.
notEmptyEmitted when a field transitions from being empty to having data.
cardTypeChangeEmitted when the possible card type changes. Only emitted from a change in the number field.
validityChangeEmitted when the validity of a field changes.
inputSubmitRequestEmitted when the customer requests submission of an input field, such as by pressing the Enter or Return key on their keyboard or the mobile equivalent.

Set up an event listener using the Hosted Fields on function after you create your Hosted Fields instance. You can use the event object to get information about your fields and update your UI accordingly. Here's how you might use cardTypeChange to update your cvv label and placeholder.

  1. Async/Await
async function setupCardTypeChange() {
  try {
    const hostedFieldsInstance = await braintree.hostedFields.create({ /* ... */ });
    const cvvLabel = document.querySelector('label[for="cvv"]'); // The label for your CVV field

    hostedFieldsInstance.on('cardTypeChange', function (event) {
      // This event is fired whenever a change in card type is detected.
      // It will only ever be fired from the number field.
      let cvvText;

      if (event.cards.length === 1) {
        cvvText = event.cards[0].code.name;
      } else {
        cvvText = 'CVV';
      }

      cvvLabel.innerHTML = cvvText;
      hostedFieldsInstance.setAttribute({
        field: 'cvv',
        attribute: 'placeholder',
        value: cvvText
      });
    });
  } catch (err) {
    // Handle error
  }
}

The CVV field's label and placeholder update to match the detected card type.

If you want to get the state of your form without using events, use the getState function. This example uses getState to confirm that all of the provided fields are valid before form submission.

  1. Async/Await
const form = document.querySelector('#my-sample-form');

async function setupFormValidation() {
  try {
    const hostedFieldsInstance = await braintree.hostedFields.create({ /* ... */ });
    form.addEventListener('submit', function (event) {
      const state = hostedFieldsInstance.getState();
      const formValid = Object.keys(state.fields).every(function (key) {
        return state.fields[key].isValid;
      });

      if (formValid) {
        // Tokenize Hosted Fields
      } else {
        // Let the customer know their fields are invalid
      }
    });
  } catch (err) {
    // Handle error
  }
}

For more sample code, see the Hosted Fields examples.

See the Hosted Fields reference for more details about events.