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 name Description
focus Emitted when a field gains focus.
blur Emitted when a field loses focus.
empty Emitted when a field transitions from having data to being empty.
notEmpty Emitted when a field transitions from being empty to having data.
cardTypeChange Emitted when the possible card type has changed. Only emitted from a change in the number field.
validityChange Emitted when the validity of a field changes.
inputSubmitRequest Emitted when the customer requests submission of an input field, such as by pressing the Enter or Return key on their keyboard or mobile equivalent.

Set up an event listener using the Hosted Fields on function in your create callback. 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.

JavaScript
Copy
Copied
braintree.hostedFields.create({ /* ... */ }, function (err, hostedFieldsInstance) {
  var 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.
    var 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
    });
  });
});

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.

JavaScript
Copy
Copied
var form = document.querySelector('#my-sample-form');

braintree.hostedFields.create({ /* ... */ }, function (err, hostedFieldsInstance) {
  form.addEventListener('submit', function (event) {
    var state = hostedFieldsInstance.getState();
    var 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
    }
  });
});

For more sample code, check out our Hosted Fields examples.

See the Hosted Fields reference for more details about events.

Next: Troubleshooting and FAQ →

Still have questions?

If you can’t find an answer, contact our Support team.