How to Run Custom Scripts on Form Submission

Follow

These hooks run your own JavaScript at a set point when a Classic Builder form is submitted. Use them to change form data before it's submitted, or to make API calls or other requests after a submission.

Unbounce logo: circular blue icon with white zero/power symbol

This is community code, not an official Unbounce feature. Unbounce Support can't troubleshoot custom code. Test it on a published page before relying on it, and work with a developer if you aren't comfortable editing JavaScript.

How the hooks work

There are two hooks, depending on when your code should run.

  • beforeFormSubmit runs after validation passes but before the lead is recorded. Use it to change form data before submission.
  • afterFormSubmit runs after the lead is recorded. Use it to make an API call or show an extra thank-you message.

Both hooks support asynchronous code. Your function can return a promise, or take a callback as its second argument and call it when the asynchronous action finishes, such as a fetch or XHR request. Form submission waits until it completes. Use this sparingly, since a slower submission can cost you leads.

Each function receives an object as its first argument, with the following properties.

  • formElement is the form's DOM element.
  • isConversionGoal is a boolean that shows whether form submission is set as a conversion goal.

If you register more than one beforeFormSubmit or afterFormSubmit hook, they run in parallel.

Examples

Use these examples as a starting point for your own hooks. Add them to the JavaScripts section.

Example 1. Trim spaces from a field before submission

<script>
  window.ub.hooks.beforeFormSubmit.push(function(args) {
    var input = args.formElement.querySelector('input#name');
    input.value = input.value.trim();
  });
</script>

Example 2. Show a message after submission

<script>
  window.ub.hooks.afterFormSubmit.push(function() {
    alert('Thank you!');
  });
</script>

Example 3. Update a field from an external API before submission

This example uses fetch to request data asynchronously.

<script>
  window.ub.hooks.beforeFormSubmit.push(function(args) {
    return fetch('https://reqres.in/api/users')
      .then(function(response) {
        return response.json();
      })
      .then(function(body) {
        return body.data[0].first_name + ' ' + body.data[0].last_name;
      })
      .catch(function() {
        return 'Unknown';
      })
      .then(function(name) {
        args.formElement.querySelector('#name').value = name;
      });
  });
</script>