Custom Javascript and CSS (Modern)

For information on how to add Custom JavaScript and CSS to your Public Pages, please see Public Page Default Settings and Public Signup Page Settings.

The following collection of code is provided as a reference, and is provided as-is. You are responsible for ensuring it works properly on your page(s), as well as maintaining this code for the future. Any modifications you make to this code, or modifications you make to code in similar sections, are your responsibility.

These snippets of code are intended as examples to show how to select and modify different elements on the Public Pages. We provide the JavaScript examples below to serve as a starting point for customizing your pages. Depending on your level of expertise, it may be necessary to engage a web developer to accomplish more complex requirements.

Each snippet has been tested in isolation. If snippets are combined with each other, or with existing custom JavaScript and CSS on your Public Pages, unexpected behavior may occur. Please test your Public Pages thoroughly to make sure the behavior satisfies your requirements.

If you are interested in viewing more JavaScript snippets that are specific to certain billing scenarios, we recommend checking out our sample product setups here.. This section offers some specific in-depth workflows that we provide as a starting point to customize your sites.

Please do not include <script> tags in your entries. Chargify automatically inserts this tag on your behalf.

JavaScript Examples

Limit Signups to US

This JavaScript code will limit both the billing and shipping country dropdown to only have US selectable.

$(function() {
  $('.form__field--country select').find('option').remove();
  $('.form__field--country select').append('<option value="US" checked="checked">United States</option>');
  $('.form__field--country select').change();
});

Adding Custom Validations

This code will allow you to set specific fields as required on the Public Pages. In the example below, we are requiring a custom field with ID 17640.

//Replace the number after `subscription_metafields_` with the ID of the custom field that needs to be required
var field1 = $("#subscription_metafields_17640");
var form = $("#signup-form");
var submitBtn = $("#subscription_submit");

$(document).ready(function() {
  var fieldLabel1 = $('label[for="subscription_metafields_17640"]');
  fieldLabel1.text(fieldLabel1.text() + " *");
});

submitBtn.click(function() {
  if (field1.val() === "") {
    field1.parent().addClass("has-error");
    field1.parent().append('<span class="error-message">cannot be blank</span>')
    return false;
  }
});

form.change(function(){
  if (field1.val() != "") {
    submitBtn.click(function() {
      return true;
    });
  }
});

field1.blur(function() {
  if ($(this).val() !== "") {
    $(this).parent().removeClass("has-error");
  } else {
    $(this).parent().addClass("has-error");
  }
});

Require Organization

This snippet will require that a potential subscriber enter data in the organization field.

var orgfield = $("#subscription_customer_attributes_organization");
var form = $("#signup-form");
var submitBtn = $("#subscription_submit");

$(document).ready(function() {
  var orgfieldLabel = $('label[for="subscription_customer_attributes_organization"]');
  orgfieldLabel.text(orgfieldLabel.text() + " *");
});

submitBtn.click(function() {
  if (orgfield.val() === "") {
    orgfield.parent().addClass("has-error");
    orgfield.parent().append('<span class="error-message">cannot be blank</span>')
    return false;
  }
});

form.change(function(){
  if (orgfield.val() != "") {
    submitBtn.click(function() {
      return true;
    });
  }
});

orgfield.blur(function() {
  if ($(this).val() !== "") {
    $(this).parent().removeClass("has-error");
  } else {
    $(this).parent().addClass("has-error");
  }
});

Require Phone Number

This snippet will require that a potential subscriber enter data in the phone field. Please be aware that this will not require a 10 digit number. If you wish to require a certain length phone number, we recommend using the JS for “Require 10 Digit Phone Field”.

var phoneField = $("#subscription_customer_attributes_phone");
var form = $("#signup-form");
var submitBtn = $("#subscription_submit");

$(document).ready(function() {
  var phoneFieldLabel = $('label[for="subscription_customer_attributes_phone"]');
  phoneFieldLabel.text(phoneFieldLabel.text() + " *");
});

submitBtn.click(function() {
  if (phoneField.val() === "") {
    phoneField.parent().addClass("has-error");
    phoneField.parent().append('<span class="error-message">cannot be blank</span>');
    return false;
  }
});

form.change(function(){
  if (phoneField.val() != "") {
    submitBtn.click(function() {
      return true;
    });
  }
});

phoneField.blur(function() {
  if ($(this).val() !== "") {
    $(this).parent().removeClass("has-error");
  } else {
    $(this).parent().addClass("has-error");
  }
});

Require 10 Digit Phone Field

This snippet will require a potential subscriber to enter a 10-digit phone number. Please be aware that you will need to add the additional CSS snippet below this to highlight the missing required digits in the phone field.

The “Custom Validations” snippet above will accept “1” as a valid phone number. This snippet will require the full 10 digits of a phone number to be entered to condsider the signup to be valid.

var form = $("form:first");
var phone = $("#subscription_customer_attributes_phone");
var submitbtn = $("#subscription_submit");

$(document).ready(function(){
	var phoneLabel = $('label[for="subscription_customer_attributes_phone"]');
	phoneLabel.text(phoneLabel.text() + " *");
});

submitbtn.click(function(){
	if (phone.val() === "") {
       phone.addClass("field-error");
       return false;
    }
	if (phone.val().length < 10) {
       phone.addClass("field-error");
       return false;
    }
});

form.change(function(){
  if(phone.val() != ""){
    submitbtn.click(function(){
       return true;
    });
  }
});

$(phone).blur(function(){
   if ($(this).val() !== "") {
       $(this).removeClass("field-error");
   } else {
       $(this).addClass("field-error");
   }
});

This is the CSS required for highlighting the required phone field if it’s missed.

.field-error
{
 color: #f00 !important;
 background: rgba(255, 0, 0, 0.5) !important;
 border: solid 1px #333 !important;
}

Reordering Components

Presently, Chargify orders components alphabetically on Public Signup Pages. With the snippet below, you can re-order the components however you prefer.

//This assigns classes to each component. 0 is the first component on the page, 1 is the second, etc.
$('.form__field--boxed').eq(0).addClass('First');
$('.form__field--boxed').eq(1).addClass('Fourth');
$('.form__field--boxed').eq(2).addClass('Second');
$('.form__field--boxed').eq(3).addClass('Third');

//This selects the component labeled with the 'Second' class and inserts it after the component labeled with the 'First' class
$('.form__field--boxed.Second').insertAfter('.form__field--boxed.First');

//At this point the order would be First, Second, Fourth, Third

//This selects the component labeled 'Third' and inserts it before the component labeled 'Fourth'
$('.form__field--boxed.Third').insertBefore('.form__field--boxed.Fourth');

Capturing Custom Field Data via Query String

With a small amount of JS, you can populate a custom field for a new signup via a Public Signup Page. The examples below use a custom field called sales.

Additionally, you’ll need to populate / replace the id of subscription_metafields_10463. Simply replace 10463 with the ID of your custom field in your site.

function getUrlVars() {
  var vars = {};
  var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
    vars[key] = value;
  });
  return vars;
}

var sales = getUrlVars()["sales"];
$(function() {
  if (sales) {
    $("#subscription_metafields_10463").val(sales);
  }
});

//this will hide the entire Custom Field section
$(".form__section--additional-information").hide();

For a full overview, and to understand more of this workflow, we require you to view full instructions on how to implement this workflow.

Hide Recurring Fee in Summary Information

This will hide the recurring charges. This method is incredibly useful if you wish to offer a gift subscription that should only obtained via a coupon, resulting in a charge of $0.00.

function hideRecurringFee() {
  $('#summary-recurring-charges').hide();
};

hideRecurringFee();
$(document).bind("afterSummaryRefresh", hideRecurringFee);

Hide Recurring Fee and Component Charges in Summary Information

This will hide the recurring charges and component charges on the Public Page.

function hideRecurringLineItem() {
  $('#summary-recurring-charges').hide();
  $('.plan__summary-component').hide();
};

hideRecurringLineItem();
$(document).bind("afterSummaryRefresh", hideRecurringLineItem);

Hide “None” Choice on Custom Fields

The following JS will remove the option to select “None” in the custom field dropdown. The first choice will be the first choice on the list of options the merchant has created. XXXX should be replaced with the custom field ID.

$(function() { 
  $("#subscription_metafields_xxxx option[value='']").remove();
  $("#subscription_metafields_xxxx option[value='']").remove();
  $("#subscription_metafields_xxxx option[value='']").remove();
});

Change Label Text

This will change the text of a label on your Public Page. The example code shown is for the Organization label.

$(function() {
  var organizationLabel = $("label[for='subscription_customer_attributes_organization']");
  organizationLabel.text("Place Text Here");
});

Change Setup Fee Text

This will change the setup fee text to be anything you want it to be.

// Just put what you want the setup fee text to be in the PLACE TEXT HERE placeholder

function changeSetupFee() {
  var setupfee = $("#summary-setup-fee .plan__summary-table-row-label");
  var text = setupfee.text().replace('Setup Fee', 'PLACE TEXT HERE');
  setupfee.text(text);
};

changeSetupFee();
$(document).bind("afterSummaryRefresh", changeSetupFee);

Change Submit Button Text

This will change the submit button text from the default “Place My Order” to anything you want it to be.

$(function() {
  var submitBtn = $("#subscription_submit");
  submitBtn.html('PLACE TEXT HERE');
});

Change Today’s Total Text

This will change the Today’s Total text to add USD, or the currency of your choice in the Public Signup Page.

function addUsd() {
  $('#todays-charge > td:nth-child(2)').append(' USD');
};

addUsd();
$(document).bind("afterSummaryRefresh", addUsd);

Force Two Components to be Equal

In case you ever need to have one component equal the same value as another you can use this script to accomplish the task.

//Just place the Component IDS of the components in the XXX's
//NOTE: both components need to be apart of the same product family

$(function () {
  var component1 = $("#component_allocated_quantity_XXX");
  var component2 = $("#component_allocated_quantity_XXX");
  
 component1.change(function(){
    component2.val($(this).val());
  });

});

Force Component to Equal Specific Number

/*Force quantity of 1 in component box on hosted page*/
$(function () {

  var updateTotal = $("#apply_component_button");
  var component = $("#component_allocated_quantity_462149");

  component.val(1);

  component.change(function () {
    component.val(1);
    updateTotal.click();
  });
});

Allow a single selection of a group of on/off components on Public Signup Pages

This is an example of limiting selection of a set of on/off components on Chargify hosted pages to select only a single component. This script can be utilized by adding it to your “Custom Javascript” on the “Public Signup Pages” found under the “Settings” tab.

This script will alter the behavior of how the radio buttons work.

Note if your customer turns off javascript there is no to protect against this. Here is the example of how to achieve it:

$(function() {
  var updatingCheckboxes = false,
  $components = $('.component-checkbox');

  $('.toggle--on-off').on('click', function(e) {
    if (updatingCheckboxes) { return; }

    var $el = $(this),
    checked = $el.is(':checked');

    if (checked) {
      e.preventDefault();
      updatingCheckboxes = true;

      // Set all on/off components to unchecked state
      $components.prop("checked", false);
      $components.parent().removeClass('btn-success').addClass('btn-default');
      $('.toggle__text').text('Add');

      // Set selected component to checked state
      $el.prop("checked", true);
      $el.parent().removeClass('btn-default').addClass('btn-success');
      $('.toggle__text', $el).text(!checked ? 'Select' : 'Selected');
      
      updatingCheckboxes = false;
    }
  });
});

Change wording on receipt page after signup

$('body > div.wrapper > div.success-receipt > div.success-receipt__heading').append("INSERT TEXT YOU WOULD LIKE TO SEE ON RECEIPT PAGE");

Remove “this product expires in 1 day” message on Public Signup Page

function hideExpirationMessage() {
 $('.plan__summary-total-description').hide();
};

hideExpirationMessage();
$(document).bind("afterSummaryRefresh", hideExpirationMessage);

Language Translations

You will need to input the translation and put in in the Custom Javascript box in the Public Signup Page. Everything that is uppercase is where you would put the translation for that field.

// CONFIGURE YOUR PLAN
$('.form__section--configure-plan h3').html("CONFIGURE YOUR PLAN");
$('#form__section-apply-components').html("UPDATE TOTALS");
$('#form__section-apply-components').data("loading-text", "<i class='fa fa-refresh fa-spin fa-fw'></i> UPDATING...");
$('#form__section-apply-components').data("button-text", "UPDATE TOTALS");

// COUPON CODE
$('.form__section--coupon h3').html("COUPON CODE");
$('#coupon_button').html("APPLY CODE");
$('#coupon_button').data("loading-text", "<i class='fa fa-refresh fa-spin fa-fw'></i> APPLYING...");
$('#coupon_button').data("button-text", "APPLY CODE");

// VAT INFORMATION
$('.form__section--vat-information h3').html("VAT INFORMATION");
$('#vat_button').html("VALIDATE VAT");
$('#vat_button').data("loading-text", "<i class='fa fa-refresh fa-spin fa-fw'></i> VALIDATING...");
$('#vat_button').data("button-text", "VALIDATE VAT");

// CUSTOMER INFORMATION
$('.form__section--customer-information h3').html("CUSTOMER INFORMATION");
$('label[for="subscription_customer_attributes_first_name"]').html("FIRST NAME *"); 
$('label[for="subscription_customer_attributes_last_name"]').html("LAST NAME *"); 
$('label[for="subscription_customer_attributes_email"]').html("EMAIL ADDRESS *"); 
$('label[for="subscription_customer_attributes_phone"]').html("PHONE"); 
$('label[for="subscription_customer_attributes_organization"]').html("ORGANIZATION");

$('label[for="subscription_customer_attributes_address"]').html("SHIPPING ADDRESS 1 *"); 
$('label[for="subscription_customer_attributes_address_2"]').html("SHIPPING ADDRESS 2"); 
$('label[for="subscription_customer_attributes_city"]').html("SHIPPING CITY *"); 
$('label[for="subscription_customer_attributes_country"]').html("SHIPPING COUNTRY *"); 
$('#subscription_customer_attributes_country').find('option').html("COUNTRY"); 
$('label[for="subscription_customer_attributes_state"]').html("SHIPPING STATE *"); 
$('#subscription_customer_attributes_state').find('option').html("STATE"); 
$('label[for="subscription_customer_attributes_zip"]').html("SHIPPING ZIP CODE"); 

// BILLING INFORMATION
$('.form__section--billing-information h3').html("BILLING INFORMATION");
$('.form__section--billing-information p:first').html("ALL TRANSACTIONS ARE SECURE AND ENCRYPTED.");
$('.form__section--credit-card .form__header-section--title').html('CREDIT CARD');

$('label[for="subscription_payment_profile_attributes_first_name"]').html("FIRST NAME ON ACCOUNT *");
$('label[for="subscription_payment_profile_attributes_last_name"]').html("LAST NAME ON ACCOUNT *");
$('label[for="subscription_payment_profile_attributes_full_number"]').html("CARD NUMBER *");
$('label[for="subscription_payment_profile_attributes_cvv"]').html("CVV");
$('label[for="subscription_payment_profile_attributes_expiration_month"]').html("EXPIRATION MONTH *");
$('label[for="subscription_payment_profile_attributes_expiration_year"]').html("EXPIRATION YEAR *");

// BILLING ADDRESS
$('.form__section--billing-address h3').html("BILLING ADDRESS");
$('.form__section--billing-address header label:first').contents().last().replaceWith("USE SHIPPING ADDRESS");
$('.form__section--billing-address header label:last').contents().last().replaceWith("USE A DIFFERENT BILLING ADDRESS");

$('label[for="subscription_payment_profile_attributes_billing_address"]').html("BILLING ADDRESS 1 *");
$('label[for="subscription_payment_profile_attributes_billing_address_2"]').html("BILLING ADDRESS 2");
$('label[for="subscription_payment_profile_attributes_billing_city"]').html("CITY *");
$('label[for="subscription_payment_profile_attributes_billing_country"]').html("COUNTRY *");
$('#subscription_payment_profile_attributes_billing_country').find('option').html("COUNTRY");
$('label[for="subscription_payment_profile_attributes_billing_state"]').html("STATE *");
$('#subscription_payment_profile_attributes_billing_state').find('option').html("STATE");
$('label[for="subscription_payment_profile_attributes_billing_zip"]').html("ZIP CODE");

// ADDITIONAL INFORMATION
$('.form__section--additional-information h3').html("ADDITIONAL INFORMATION");

// TERMS
$('.form__section--terms-submit label').contents().slice(3).remove();
$('.form__section--terms-submit label').append('I ACCEPT THE <a href="" target="_blank">TERMS AND CONDITIONS</a>');

// SUBMIT
$('#subscription_submit').html("PLACE MY ORDER");

// PLAN SUMMARY
$('.content__secondary .content__heading h2').html("PLAN SUMMARY");

JQuery

Chargify supports the usage of JQuery on your Public Signup Pages.

For example, if you’d like to include a third-party script that is hosted elsewhere, you can use the JQuery.getscript function to load a JavaScript file from the server using a GET HTTP request, then execute it.

  $.getScript( "https://cdn.example.com/test.js" )
    .done(function( script, textStatus ) {
      console.log( textStatus );
    })
    .fail(function( jqxhr, settings, exception ) {
      $( "div.log" ).text( "Triggered ajaxError handler." );
  });


CSS Examples

Hide One or More Components

In this example, the number in square brackets refers to the components ordered on the page, where 0 is the first component and 1 is the second component.

$($('.form__field--boxed')[0]).hide(); // hides first component
$($('.form__field--boxed')[1]).hide(); // hides second component

Signup Page CSS Classes

The following is a list of all CSS classes used on the Public Signup Page.

/*
  Name: PSP CSS Cheatsheet
  Author: Bob Orchard
*/

/* Body Classes */
.public-signup-page {} /* Both Signup and Success Pages */
.public-signup-page__signup {}
.public-signup-page__success {}

/* Wrapper: Container that centers the form*/
.wrapper {
  /* Make Form Full-Width */
  /* max-width: 100%; */
}

/* Header: Contains logo/logo text and SSL notice (if enabled) */
.header {}
.header__logo {}
.header__logo h1 {}
.header__logo img {}
.header__ssl-notice {}

.content__headings {
  /* Desktop: When scrolling, these headings attach themselves to the top of the window */
  /* Mobile/Tablet: Hidden */
}

/* Plan Summary Wrapper */
.plan__summary {}
.plan__summary-table {}
.plan__summary-table-row {}
.plan__summary-table-row-label {}
.plan__summary-table-row-total {}
.plan__summary-total {}
.plan__summary-total-description {}

/* Plan Summary Items */
.plan__summary-initial {}
.plan__summary-baseline {}
.plan__summary-component {}
.plan__summary-tax {}

/* Main Content - Contains both the main form and the summary in the sidebar to the right */
.content {}
.content__main {}
.content__secondary {}
.content__heading { /* Main Heading in both .content__main and .content__secondary */ }
.content__heading--mobile { /* Mobile/Tablet: Mobile Heading that sticks to the top of the window */ }
.content__heading-section--total { /* Mobile/Tablet: Mobile Heading total that sticks to the top of the window */ }
.content__signup-form { /* Signup Form Wrapper */ }

.form__section {}
.form__section--product-description {}
.form__section--configure-plan {}
.form__section--apply-coupon {}
.form__section--customer-information {}
.form__section--vat-information {}
.form__section--shipping-information {}
.form__section--billing-information {}
.form__section--billing-address {}
.form__section--terms-submit {}

.form__fields { /* Wrapper for a group of fields */ }
.form__field { /* Individual input field */ }

.form__fields--name {}
.form__field--first-name {}
.form__field--last-name {}

.form__fields--address {}
.form__field--address {}
.form__field--address2 {}
.form__field--country {}
.form__fields--city-state-zip {}
.form__field--city {}
.form__field--state {}
.form__field--zip {}
.form__field--email {}
.form__field--phone {}
.form__field--organization-name {}

.form__fields--apply-vat {}
.form__field--vat-number {}

.form__field--credit-card-number {}
.form__fields--credit-card-details {}
.form__fields--credit-card-cvv {}
.form__fields--credit-card-expiration-month {}
.form__fields--credit-card-expiration-year {}

.form__field--bank-name {}
.form__fields--bank-information {}
.form__field--routing-number {}
.form__field--account-number {}

.form__button {}
.form__button--primary {}
.form__button--large {}
.form__button--is-submitting {}

.success-receipt {}
.success-receipt__icon {}
.success-receipt__icon--success {}
.success-receipt__heading {}
.success-receipt__items {}
.success-receipt__total {}
.success-receipt__home-link {}

/* All Accent Colors */

.plan__summary-total,
.content__heading-section--total,
.success-receipt__icon .fa-check,
.success-receipt__total dl:last-of-type {
  color: red;
}

.form__button--primary {
  background: red;
  border: red;
}

.form__button--primary:hover,
.form__button--primary:active,
.form__button--primary:focus,
.form__button--primary:disabled {
  background: #990000;
}

Signup Page CSS IDs

The following is a list of all CSS IDs used on the Public Signup Page.

/* Plan Summary */
#mobile_summary {}
#summary {}
#summary-setup-fee {}
#summary-recurring-charges {}
#todays-charge {}

/* Plan Configuration */
#components_XXX_allocated_quantity { /* On/Off Components */ }
#component_allocated_quantity_XXX { /* Metered & Quantity-Based Components */ }

/* Coupons */
#long_coupon_message {}
#coupon_code {}
#coupon_button {}

/* VAT Information */
#long_vat_message {}
#subscription_customer_attributes_vat_number {}
#vat_button {}

/* Customer Information */
#subscription_customer_attributes_first_name {}
#subscription_customer_attributes_last_name {}
#subscription_customer_attributes_email {}
#subscription_customer_attributes_phone {}
#subscription_customer_attributes_organization {}

#subscription_customer_attributes_address {}
#subscription_customer_attributes_address_2 {}
#subscription_customer_attributes_country {}
#subscription_customer_attributes_city {}
#subscription_customer_attributes_state {}
#subscription_customer_attributes_zip {}

/* Billing Information */
#credit_card_logos {}

#subscription_payment_profile_attributes_first_name {}
#subscription_payment_profile_attributes_last_name {}
#subscription_payment_profile_attributes_full_number {}
#subscription_payment_profile_attributes_cvv {}
#subscription_payment_profile_attributes_expiration_month {}
#subscription_payment_profile_attributes_expiration_year {}

#use_shipping_address_1 {}
#use_shipping_address_0 {}

#subscription_payment_profile_attributes_billing_address {}
#subscription_payment_profile_attributes_billing_address_2 {}
#subscription_payment_profile_attributes_billing_country {}
#subscription_payment_profile_attributes_billing_city {}
#subscription_payment_profile_attributes_billing_state {}
#subscription_payment_profile_attributes_billing_zip {}

/* Custom Fields */
#subscription_metafields_XXX {}

/* Terms and Conditions */
#accept_terms {}

/* Submit Button */
#subscription_submit {}