Custom JavaScript and CSS (Classic)

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

These snippets of code are intended as examples to show how to select and modify different elements on the Public Pages. Chargify Support can provide assistance with simple changes such as hiding a field or restricting the country location for new signups. 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.

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) {
		$("#metafield_10463").val(sales);
	}
});

//this will hide the entire Custom Field section
$('.metafield_configuration').hide();
$('#contact_info+ h2').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.

Limit Signups to US

This JavaScript code will limit the country dropdown to only have US selectable.

//Limits both Billing and Shipping Countries to the US

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

Remove Puerto Rico from state list

// Removes Puerto Rico from list of states that can be selected

$(function() 
{
   $('.country_select').find('[value="PR"]').remove();
   $('.country_select').change();
});

Show Bank Account by Default on Self-service Page

This code affects Self-service Pages in particular, and is a way to have bank accounts show first on the page. By default, the credit card option is displayed immediately, and changing to a bank account method requires clicking the “Change Payment Method” link.

$(function() { 
  $('#change_payment_method > p > a').click();
  $('#pay_by_ach_btn').click(); 
});

Require Custom Fields on Public Pages

This code will allow a Text Field type Custom Field to be required on the Public Pages. You will need to know the ID of the Custom Field. To find the ID, go to the Setup tab, click Custom Fields, then click Edit to the right of the field you are interested in. The ID number will be in the URL. Replace XXX with this ID in the code below.

In addition to the Custom JavaScript, lines 34-39 show the Custom CSS that is needed to make the field turn red if the customer submits the form without entering anything.

// EXAMPLE of ID in the URL https://subdomain.chargify.com/setup/metafields/1033/edit

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

});

var customobj1 = $("#metafield_XXX");

var form = $("#hosted-payment-form");

var submitbtn = $("#subscription_submit")

 submitbtn.click(function(){
    if (customobj1.val() === "") {
        customobj1.addClass("field-error");
        return false;
    }
});

form.change(function(){
   if(customobj1.val() != ""){
       customobj1.removeClass("field-error");
       submitbtn.click(function(){
        return true;
       });
   } else {
      return false;
   }
});

CSS:

.field-error
{
  color: #b94a48 !important;
  background: #f2dede !important;
  border: solid 1px #eed3d7 !important;
}

Require Organization Field

This code will allow the Organization field to be required on the Public Pages. You will need to add the CSS from the second snippet to your Custom CSS box for the field to turn red if a customer does not provide a value for the Organization field.

You would need to replace each of the metafield values [REPLACE_ID] values in the subscription_metafields reference to match your custom field / metafield ID.

Then, if you have more than 1 custom field, you would need to reuse the code and change all the “customLabel1” and “customobj1” values to be “customLabel2” and “customobj2”.

$(document).ready(function(){
  
var customLabel1 = $("label[for='subscription_metafields_[REPLACE_ID]']");
  customLabel1.text(customLabel1.text() + " *");
});
var customobj1 = $("#subscription_metafields_20974");
var form = $("#hosted-payment-form");
var submitbtn = $("#subscription_submit");
 submitbtn.click(function(){
    if (customobj1.val() === "") {
        customobj1.addClass("field-error");
        $("<p style='color:red;'>Cannot be blank</p>").insertAfter("#subscription_metafields_[REPLACE_ID]");
        return false;
    }
});
form.change(function(){
   if(customobj1.val() != ""){
       customobj1.removeClass("field-error");
       submitbtn.click(function(){
        return true;
       });
   } else {
      return false;
   }
});

CSS:

.field-error
{
  border-style: solid;
  border-color: red;
}

Require Phone Field

This code will allow the Phone Number field to be required on the Public Pages. You will need to add the CSS from lines 35-40 to your Custom CSS box for the field to turn red if a customer does not provide a value for the Phone Number field.

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

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

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

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

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

CSS:

.field-error
{
  color: #b94a48 !important;
  background: #f2dede !important;
  border: solid 1px #eed3d7 !important;
}

Hide Summary Information

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

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

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

Hide Specific Field

This will hide a specific field from the Public Signup Page:

$("#subscription_payment_profile_attributes_cvv").hide();
$('label[for="subscription_payment_profile_attributes_cvv"]').hide();

To locate the list of available IDs, please view CSS IDs, here.

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");
    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.

// Place what you want the submit button to say in the PLACE TEXT HERE placeholder

$(function() {
 var submitbtn = $("#subscription_submit");
 submitbtn.attr('value', 'PLACE TEXT HERE');
});

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());
  });

});

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

Copy/paste the following CSS into your Public Page.


.tint { display: none; }

Simple CSS to fix size issues

This was contributed by one of our most active users, Kori Francis, who is also the author of Chargify.Net sample code. It fixes a few issues with the hosted page CSS (including the select size being different):

div.section_three input,
div.section_four input, div.section_three select {
background: #f5f5f5;
border: 1px solid #ccc;
-webkit-border-radius: 5px; -moz-border-radius: 5px; resize: none; }

* html input { overflow: visible; padding: 5px;}

div.section_three select {
margin-top: 5px;
padding: 6px;
}

div.section_three input:focus,
div.section_four input:focus, div.section_three select:focus {
background: #fff;
}

Though, it works for everything excluding IE - there’s an issue in IE where the text is placed strangely.

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');
  $components.change(function(e) {
    if(updatingCheckboxes) { return; }
    var $el     = $(this),
        checked = $el.attr("checked");
    if(checked) {
      e.preventDefault();
      updatingCheckboxes = true;
      $components.attr("checked", false);
      $el.attr("checked", true);
      updatingCheckboxes = false;
    }
  });
});

Adding Custom Validations

This can easily be done by adding a little custom javascript to your “Public Signup Page Settings” under the “Settings” tab.

$(function() {


  var $form      = $("form#hosted-payment-form"),
      $submit    = $form.find("input[type='submit']"),
      $label     = $form.find("label[for='subscription_payment_profile_attributes_billing_zip']"),
      submitText = $submit.val();

  // Mark billing zip as required
  $label.text("*" + $label.text());

  // Errors that you wish to display
  var $errorExplanation = $('<div class="errorExplanation" id="errorExplanation"><h2>There were problems with your submission</h2><p>Please correct the following problems:</p><ul><li>Billing Zip: cannot be blank.</li></ul></div>');

  $form.submit(function(e) {
    // Make sure to not double add the errors
    $('errorExplanation').remove();

    console.log("clicked");
    // don't submit the form if billing zip is empty
    if($.trim($form.find("input#subscription_payment_profile_attributes_billing_zip").val()).length == 0) {
      e.preventDefault();
      $errorExplanation.insertAfter("#hosted-description");
      $submit.val(submitText);
      // make button clickable again
      $submit.attr("disabled", false);
    }
  });

});

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.

//Billing information form
$('#hosted-payment-form h2:first').html("CONFIGURE YOUR PLAN:");
$('label[for="subscription_payment_profile_attributes_full_number"]').html("* FULL CARD NUMBER");
$('label[for="subscription_payment_profile_attributes_expiration_month"]').html("* EXPIRATION DATE");
$('#apply_component_button' ).html( "UPDATE TOTALS" );
$('#summary' ).bind( 'ajaxComplete', function() {  
$('#summary > h2' ).html( "PURCHASE SUMMARY:" );
var todaysTotal = $('#total h3' ).html();
todaysTotal = todaysTotal.replace( "Today's Total", "TODAY's TOTAL" );
$('#total h3' ).html( todaysTotal );
} );
$('#summary' ).next( 'h2' ).html( "BILLING INFORMATION:" );
$('.section_three').next('h2').html("BILLING ADDRESS:" );
$('label[for="subscription_payment_profile_attributes_first_name"]').html( "FIRST NAME ON CARD" );
$('label[for="subscription_payment_profile_attributes_last_name"]').html( "LAST NAME ON CARD" );
$('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" );
$('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" );
$('label[for="subscription_coupon_code"]').html( "COUPON CODE" );
$('#coupon_button').html( "VALIDATE COUPON" );

// Contact information form
$( '.section_four' ).prev( 'h2' ).html( "CONTACT 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" );

$( '#accept_terms' ).next( 'label' ).html( 'ACCEPT TERMS <a target="blank" href="">TERMS</a>' );

$( '#subscription_submit' ).val( "PLACE MY ORDER" );

Require VAT Number

$("#hosted-payment-form").submit(function(e){
if($("#subscription_vat_number").val() == ""){
alert("Please enter a valid VAT number");
e.stopImmediatePropagation();
return false;
}else{
return true;
}
});

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

Signup Page CSS Classes

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

  • new_subscription
  • company_name
  • hidden
  • component_configuration
  • row
  • left
  • component-label
  • component-description
  • quantity_component_number_field
  • component-info
  • component-multiplier
  • component-price
  • componentError
  • priceDetails tip
  • component-price-list
  • component-checkbox
  • checkbox component-price
  • section_one
  • line-item_initial
  • line-item_baseline
  • tint
  • section_two
  • right
  • address shipping_address
  • country_select address shipping_address
  • subdivision_select address shipping_address
  • use-ship-label
  • section_three
  • hint
  • section_four
  • metafield_configuration
  • button_wrapper
  • powered-by-chargify

Signup Page CSS IDs

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

  • page_wrapper
  • page_column
  • security
  • content
  • company
  • hosted-payment-form
  • token
  • component_configuration
  • component_row_####
  • components__component_id
  • component_allocated_quantity_####
  • component_errors_####
  • component_price_list_####
  • on_off_component_####
  • component_checkbox_####
  • apply_component_button
  • summary
  • billing_summary
  • summary-setup-fee
  • summary-recurring-charges
  • total
  • todays-charge
  • expiration-date
  • subscription_ref
  • subscription_customer_attributes_first_name
  • subscription_customer_attributes_last_name
  • subscription_customer_attributes_address
  • subscription_customer_attributes_address_2
  • subscription_customer_attributes_country
  • subscription_customer_attributes_state
  • subscription_customer_attributes_city
  • subscription_customer_attributes_zip
  • copy-address
  • billing_info
  • subscription_coupon_code
  • coupon_button
  • coupon_spinner
  • short_coupon_message
  • long_coupon_message
  • payment_type
  • subscription_payment_profile_attributes_first_name
  • subscription_payment_profile_attributes_last_name
  • credit_card_info
  • subscription_payment_profile_attributes_full_number
  • credit_card_logos
  • subscription_payment_profile_attributes_cvv
  • subscription_payment_profile_attributes_expiration_month
  • subscription_payment_profile_attributes_expiration_year
  • subscription_payment_profile_attributes_billing_zip
  • contact_info
  • subscription_customer_attributes_email
  • subscription_customer_attributes_reference
  • subscription_customer_attributes_phone
  • subscription_customer_attributes_organization
  • metafield_####
  • product_id
  • subscription_submit
  • footer