JavaScript Code Samples

In this article, you'll find some commonly used snippets of JavaScript and HTML code that you can use when implementing sites hosted on this service.

Please note that the following code samples are provided as a guide only; the code may require customization to work with your site. You must be proficient in JavaScript implementation, because support is not provided for the implementation of these items.

When inserting JavaScript on your page, make sure to paste the sample code at the end of your HTML document to ensure all page elements are rendered before the script is run. Otherwise, the scripts may cause errors. Always keep track of the most recent working backup copy of the page, so that you can revert to the archived version if you add code that does not work on a page.

To learn more about rolling back to a previous iteration of an archived page, see Understanding web pages.

Set the value of the username field equal to the email address field

To make the visitor's email address their Secure Zone username, you'll need to edit the code in the web form. In this system, the username and the email address fields are different, and can contain different values by default. In order for the registered visitor to use their email address to login, their email address must also be stored in the Username field.

To customize a web form to automatically populate the username field with the visitor’s email address, follow these steps:

  1. Insert the web form on to a web page.
  2. Use CSS styles to hide (not remove) the Username field. You can do this by wrapping it in a HTML div element which is set to hidden. The code to hide the Username field is provided below:

    <div style= display:none;>Username<br><input type=text name="Username" ></div>
  3. Add the following code to make the email address field automatically update the Username field when an email address is entered.
<input type=text name="EmailAddress" onBlur="document.getElementById('Username').value=this.value;>

Hiding the "Shopping Cart Is Empty" message

To avoid the default message regarding the shopping cart's status, add this JavaScript to hide the catCartSummary from view:

<script type="text/javascript">
if (document.cookie && document.cookie.indexOf("CartID") < 1) {
document.getElementById('catCartSummary').style.display = "none";
}
</script>

Assigning a Web App item name to a page title

You can set the system created pages that display when drilling down to individual Web App items to display as the page's title, to make the site easier to navigate. Add the following code:

<script type="text/javascript">
function titlechange()
{
document.title = "{tag_item_name}";
}
</script>
</head>
<body onload="titlechange()">

Redirecting to another page

The following JavaScript code example redirects a visitor to various URLs of the same site to different web pages.

<script type="text/javascript">
 
var url = document.location.href.toLowerCase();
if (url.indexOf('domain1.com') != -1)
   document.location = 'http://domain1.com/index1.htm';
if (url.indexOf('domain2.com') != -1)
   document.location = 'http://domain2.com/index2.htm';
 
</script>

Logging into different Secure Zones according to ID number

You can add a menu with options that enable you to select the corresponding ID number, using some basic HTML code:

<select id="selectZone">
<option value="154">Customer</option>
<option value="150">Staff Intranet</option>
<option value="152">Kanfa Aragon</option>
<option value="168">Technip</option>
<option value="347">Heron</option>
</select>

And then, add this JavaScript to the end of the same login page:

<script language="javascript">
		
function checkWholeForm43650(theForm){ var why = "";
if (theForm.Username) why += isEmpty(theForm.Username.value, "Username"); if (theForm.Password) why += isEmpty(theForm.Password.value, "Password"); if (why != ""){ alert(why); return false; }
var sel = document.getElementById("selectZone"); theForm.action = '/ZoneProcess.aspx?ZoneID='+sel.options[sel.selectedIndex].value+'&OID={module_oid}&OTYPE={module_otype}'; theForm.submit(); return false; }
</script>

Setting the billing information to be the same as the shipping information

This script will populate the billing information in the checkout form if the customer selects the "Same as shipping" checkbox.

Add this code to the checkbox:

<input type="checkbox" onclick="SetBilling(this.checked);"/> Same as Shipping

And then, at the bottom of the page, add the following JavaScript function:

<script type="text/javascript">
function SetBilling(checked) {
	if (checked) {
		document.getElementById('BillingAddress').value = document.getElementById('ShippingAddress').value; 
		document.getElementById('BillingCity').value = document.getElementById('ShippingCity').value; 
		document.getElementById('BillingState').value = document.getElementById('ShippingState').value; 
		document.getElementById('BillingZip').value = document.getElementById('ShippingZip').value; 
		document.getElementById('BillingCountry').value = document.getElementById('ShippingCountry').value; 
	} else {
		document.getElementById('BillingAddress').value = ''; 
		document.getElementById('BillingCity').value = ''; 
		document.getElementById('BillingState').value = ''; 
		document.getElementById('BillingZip').value = ''; 
		document.getElementById('BillingCountry').value = ''; 
	}
}
</script>

Adding an email verification field to a web form

You can update a web form to require that visitors enter their email address twice, to verify it. This is similar to password verification, because the logic added to the form compares both fields to ensure they match. Open the the page the web form is and paste the following code just below the email address field:

<input id="EmailAddress2" class="cat_textbox" name="EmailAddress2" maxlength="255"/>

Then you can embed the following JavaScript code into the existing JavaScript code of the web form:

if (document.getElementById('EmailAddress').value !=document.getElementById('EmailAddress2').value) 
{
alert('- Email address and its confirmation do not match\n');
return false;
}

 The existing code looks something like this (although in your code the function name will be different):

<script type="text/javascript">
var submitcount77199 = 0;
function checkWholeForm77199(theForm)
{var why = "";if (theForm.FirstName) why += isEmpty(theForm.FirstName.value, "First Name");
if (theForm.LastName) why += isEmpty(theForm.LastName.value, "Last Name"); 
if (theForm.EmailAddress) why += checkEmail(theForm.EmailAddress.value); 
if (!theForm.PaymentMethodType || getRadioSelected(theForm.PaymentMethodType) == 1) 
{ if (theForm.CardName) why += isEmpty(theForm.CardName.value, "Name on Card"); 
if (theForm.CardNumber) why += isNumeric(theForm.CardNumber.value, "Card Number"); 
if (theForm.Amount) why += isCurrency(theForm.Amount.value, "Amount"); } 
if (theForm.PaymentMethodType) why += checkSelected(theForm.PaymentMethodType, "Payment Method");
if(why != ""){alert(why);return false;}if(submitcount77199 == 0)
{submitcount77199++;theForm.submit();return false;}
else{alert("Form submission is in progress.");return false;}}
</script>

 After you add the new JavaScript code to the existing code, it will look something like this:

<script type="text/javascript">
var submitcount77199 = 0;
function checkWholeForm77199(theForm)
{var why = "";if (theForm.FirstName) why += isEmpty(theForm.FirstName.value, "First Name");
if (theForm.LastName) why += isEmpty(theForm.LastName.value, "Last Name"); 
if (theForm.EmailAddress) why += checkEmail(theForm.EmailAddress.value); 
if (!theForm.PaymentMethodType || getRadioSelected(theForm.PaymentMethodType) == 1) 
{ if (theForm.CardName) why += isEmpty(theForm.CardName.value, "Name on Card"); 
if (theForm.CardNumber) why += isNumeric(theForm.CardNumber.value, "Card Number"); 
if (theForm.Amount) why += isCurrency(theForm.Amount.value, "Amount"); } 
if (theForm.PaymentMethodType) why += checkSelected(theForm.PaymentMethodType, "Payment Method");
if (document.getElementById('EmailAddress').value != document.getElementById('EmailAddress2').value) 
{
alert('- Email address and its confirmation do not match\n');
return false;
}
if(why != ""){alert(why);return false;}if(submitcount77199 == 0)
{submitcount77199++;theForm.submit();return false;}
else{alert("Form submission is in progress.");return false;}}
</script>

 Hiding a retail price for items that are not on sale

Add the following script to the large or small products layout for an online store:

<script language="javascript"><!--
 
 
var onsale_{tag_productid} = "{tag_onsale}";
 
if (onsale_{tag_productid} == "0") {
 document.getElementById("rrpprice_{tag_productid}").style.display = 'none'; }
 
 
//--></script>

Then you would assign the following tag ID to a retail price tag

<div id="rrpprice_{tag_productid}">{tag_retailprice}</div> 

After adding this script, the retail price will be hidden for every item that is not currently on sale.

Creating a dropdown menu for multi-currency websites

 Add this script to enable customers to choose from a list of supported currencies for an online store:

Please select Country: <select id="selectCountry" onchange="document.location=this.options[this.selectedIndex].value;">
<option value="http://www.yourURL.com/CatalogueRetrieve.aspx?CatalogueID=15789">Australia</option>
<option value="http://nz.yourURL.com/CatalogueRetrieve.aspx?CatalogueID=15789">New Zealand</option>
<option value="http://uk.yourURL.com/CatalogueRetrieve.aspx?CatalogueID=15789">United Kingdom</option>
</select>

//THE ABOVE CODE WILL PROVIDE YOU WITH A DROPDOWN THAT WILL SIMPLY REFRESH THE PAGE. THERE ARE MORE ELEGANT WAYS TO DO THIS!

<script type="text/javascript">
var country = document.location.host;
var sel =document.getElementById('selectCountry');
if (country == 'nz.yourURL' ){
sel.selectedIndex = 1;
}
else if (country == 'uk.yourURL' ){
sel.selectedIndex = 2;
}
else{
sel.selectedIndex = 0;
}
</script>

// THIS CODE WILL SELECT THE CORRECT DROPDOWN OPTION ACCORDING TO THE URL

Returning a customer to a default URL after viewing the receipt page

After a customer has made a purchase, if they continue browsing the site, the pages will be using the site's secure URL. If you want to redirect customers to a default URL, place the following script in your Receipt (Buy) online shop layout:

<script>
var siteUrl = 'http://www.yoursite.com';
var links = document.getElementsByTagName('A');

for (i = 0; i < links.length; i++)
{
	if (links[i].getAttribute('href'))
	{
		var href = links[i].getAttribute('href');
		if (href.substring(0,4) != 'http' && href.substring(0,1) == '/')
		{
			//this example requires your links to have absolute paths.
			//document-relative paths and absolute URLs are not supported.
			links[i].setAttribute('href', siteUrl + href);
		} 
	}
}

</script>

Returning a customer to a different URL based on their country selection

If your online store uses several domains with different currencies, you can modify the script above to support the different transactions. Just replace this line:

var siteUrl = 'http://www.yoursite.com';

with this code:

var siteUrl = 'http://www.yoursite.com'; //the default in case we don't match a country

if ('{module_visitorcountrycode}' == 'AU') siteUrl = 'http://www.yoursite.com.au';
if ('{module_visitorcountrycode}' == 'NZ') siteUrl = 'http://www.yoursite.co.nz';

Showing the contents of a hidden div tag if a registered visitor is logged in

Sometimes it is helpful to initially hide an element, and then check to see if the visitor is logged in. If the visitor is logged in, you can add logic to display that hidden element. In this case, you can use the {module_isloggedin} module that displays a value of 1 if customer is logged in and 0 if they are not logged in. Add the following code to hide the div container and its contents:

<div id="hiddenform" style="display:none">

...

</div>

And this is the script used to display the div container if the visitor is logged in: 

var loggedin = "{module_isloggedin}";
if  (loggedin == 1)
document.getElementById('hiddenform').style.display = "block";

Replacing Shipping options with custom text

 You can update the shopping cart to add a custom message next to the shipping options, using the code below:

<script type="text/javascript">
var sel = document.getElementById('ShippingOptions')
for(var i=sel.options.length-1;i>=0;i--)
{
if(sel.options[i].value == "-1")
    sel.options[i].text = "Here goes the text of whatever you want to replace Choose Shipping Options to";
}
</script>

 

Pre-Loading images using Javascript

 If your site includes larger file sizes, you can help improve the visitor's experience by pre-loading them before they are requested. That will reduce the latency that may occur as the larger file downloads. Add this code:

<script language="javascript">
var home = new Image();
home src="http://yourdomain.com/image.jpg"

var home-roll = new Image();
home src="http://yourdomain.com/image.jpg"

</script>

 

Auto-Selecting one Shipping Option

To auto-select a a shipping option, add the Javascript shown below to the Shopping Cart Layout:

<script type="text/javascript">
var shippingOptions = document.getElementById('ShippingOptions');
if (shippingOptions) {
   shippingOptions.selectedIndex = 1;
   shippingOptions.onchange();
}
</script>

Supressing alert windows

Use the following code with caution and be mindful where you place it, because it will supress any alert windows. For example, if you place it on a site-wide template, it will supress any alert pop-up window, which may impact the features of your site.


<script type="text/javascript">
window.alert=function(msg){}
</script>

Overriding the Checkout button on the Checkout page

If you'd like to override the default checkout button, add the following script to the Checkout Step layout. You can access this layout file by choosing Admin >More Customization Options. Click the Online Shop Layouts icon. In the list that appears, select the  Checkout Step layout. 

This script essentially allows you to add a JavaScript function before the checkout submits and the system presents the registration step.

<script type="text/javascript">
function AddEvent(func){
      var btn = document.getElementById('catshopbuy');
      var oldonclick = btn.onclick;
      if (typeof btn.onclick != 'function'){
	 btn.onclick = func;
      }
      else{
	 btn.onclick = function() {
	    func();
	    return oldonclick();
	    
	 };
     }
}

function func(){
   alert('hi');
}

AddEvent(func);

</script>

Changing the message: This product is unavailable or out of stock.

To change the message that’s displayed when the last unit of a product has been added to a cart, (in other words, when the system detects that the item is out of stock), you can change the message the system displays: This product is unavailable or out of stock.

To do this, add the following JavaScript code to a site-wide template or to the online store's Overall layout. To access the Overall layout, choose Admin > More Customization Options, and then choose the Online Shop Layouts icon.

<script type="text/javascript">
    function AddProductExtras(catalogId,productId,ret) {
	var td = document.getElementById('catProdTd_'+productId);
	if (td.innerHTML == 'This product is unavailable or out of stock.')
	   td.innerHTML = 'Product added successfully.';
	   }
</script>


		

Clearing the values of form fields when a visitor browses back to a previously submitted form

Implement the following script to make your site more secure. For example, add this code to ensure that a visitor's entries into a web form are not 'viewable' by navigating 'back' to the page after the form's submission. Place the following code on the page with the web form.

<script type="text/javascript">
var ele = document.getElementsByTagName('input');
var len = ele.length;
for(var i=0;i<len;i++){
    if(ele[i].type == 'text')
	ele[i].value='';
}    
</script>

Changing the date format to North American date format

Announcement dates

When using the Announcements module, you can use {tag_counter} to generate the item ID and to access the date. Then, you can use some JavaScript to re-format the date.

In this example, this tag {tag_eventfromdate} is reformatted, but you can use the same method for any date tag. Here is the HTML code you need to use in your announcement layout. Note that the important part is id="date{tag_counter}".

You'll add this code in the List layout. In the Detailed layout, just change the id from id="date{tag_counter} to something else, such as id="dateid".

<span id="date{tag_counter}">{tag_eventfromdate}</span>

 The JavaScript below converts the default date format (23-Apr-2009) into a North American date format: Apr/23/2009.

<script type="text/javascript">
var originalDate = document.getElementById('date{tag_counter}').innerHTML;
var dateBits = originalDate.split("-");
document.write(dateBits[1] + "/" + dateBits[0] + "/" + dateBits[2]);
</script>


		

Note: You can feed the date directly into the var originalDate like this:

var originalDate = "{tag_eventfromdate}";

Literature dates

Similar to Announcements, you can update Literature items by using {tag_counter} to generate the item ID and access the date. Then use some JavaScript to re-format the date.

In the example below, the tag {tag_expirydate} is reformatted. However, keep in mind that you can use the same method for any date tag. Here is the HTML code you need to use in your announcement layout. Note that the important part of the code is: id="date{tag_counter}".

Add this code to the List layout. In the Detailed layout, simply change the id from id="date{tag_counter} to something else, such as id="dateid".

<span id="date{tag_counter}">{tag_expirydate}</span>

The following JavaScript code will take the date formatted like this: 23-Apr-2009 and convert it to a North American date format, like this: Apr/23/2009.

<script type="text/javascript">
var originalDate = document.getElementById('date{tag_counter}').innerHTML;
var dateBits = originalDate.split("-");
document.write(dateBits[1] + "/" + dateBits[0] + "/" + dateBits[2]);
</script>

 Note: You can feed the date directly into var originalDate, like this var originalDate = "{tag_expirydate}";

Refreshing the page after adding a product to a cart

Add this code in the Site-Wide Template that your shopping cart is using (or link to this JavaScript in an external .js file).

<script type="text/javascript">
function AddProductExtras(){
document.location.reload(true);
}
</script>

Hiding the red X displayed by Internet Explorer when you have empty image fields in a Web App 

In the template or web page, place the following JavaScript in the <head> of the page.

    <script language="JavaScript">
      function ImageLoadFailed() {
	window.event.srcElement.style.display = "None";
      }
    </script>

 Then, in the Web App layout where you the image is displayed, place the following:

<img src="{tag_imagename_value}?Action=thumbnail&Width=80&Height=80"
OnError="ImageLoadFailed()" class="right" alt="{tag_name_nolink}" />


		

Capturing form fields in the special instructions box for a product

Place this code on the large product layout. You can access it by choosing Admin > More Customization Options. Then click the Online Shop Layouts. In the list that appears, click the Large Product Layout.

This special instructions text field will take three separate input lines of text and combine them into one set of special instructions, separated by commas, assuming that the product has the Capture Details option enabled.

Then, you can add the item to the cart when selecting the image. In the code below, you'll need to substitute a correct path for src="/yourcustomisedbutton.jpg" in the third line from the bottom of this code snippet. 

<html>
    <head>
	<script language="javascript">
<!--
function CollectText(){
    var gettxt1,gettxt2,gettxt3;
    gettxt1=document.getElementById("txt1").value;gettxt2=document.getElementById("txt2").value;gettxt3=document.getElementById("txt3").value;
    if(gettxt1=="" && gettxt2=="" && gettxt3==""){      
	CombinedVal="";  
    } else {      
	CombinedVal= gettxt1 + " , " + gettxt2 + " , " + gettxt3;   
    }
    document.getElementById("catProdInstructions_{tag_productid}").value=CombinedVal;
}
-->
	</script>
    </head>
    <body>
	<form>
	    Forrm Fields (for form on which you wish to capture test in separate lines)
	    <br />
	    Line 1:<br />
	    <input type="text" id="txt1" name="txt1" /><br />
	    Line 2:<br />
	    <input type="text" id="txt2" name="txt2" /><br />
	    Line 3:<br />
	    <input type="text" id="txt3" name="txt3" /><br />
	</form>
	{tag_capturedetails}
	<a href="#"><img alt="" src="/yourcustomisedbutton.jpg" onclick="CollectText(); AddToCart({tag_catalogueid},{tag_productid},'',1,false);return false;" /></a>
    </body>
</html>

 

Capturing the visitor's name and phone number only

In this example, the webform validation JavaScript was altered to capture the full name and the cell phone only. The JavaScript below will actually take the cell phone number from the cell number field, attach "@email.com" to it and populate the email field with this value. This must be done programmatically, because the form cannot be submitted without a valid email address.

Add the following line to the existing script:

document.getElementById('EmailAddress').value = document.getElementById('CellPhone').value + '@email.com';

You should also disable the auto responder by adding &SAR=False to the action URL and redirecting the visitor to a custom page by appending &PageID=/landingpage.htm to it.

Here's an example of the form code: 

<form name="catwebformform63295" method="post" onsubmit="return checkWholeForm63295(this)" enctype="multipart/form-data" action="/FormProcessv2.aspx?WebFormID=19401&OID={module_oid}&OTYPE={module_otype}&EID={module_eid}&CID={module_cid}&SAR=False&PageID=/landingpage.htm">
    <span class="req">*</span>  Required
    <table cellspacing="0" cellpadding="2" border="0" class="webform">
	<tbody>
	    <tr>
		<td><label for="FirstName">First Name <span class="req">*</span></label><br />
		<input type="text" name="FirstName" id="FullName" class="cat_textbox" maxlength="255" /></td>
	    </tr>
	    <tr>
		<td style="display: none;"><label for="EmailAddress">Email Address <span class="req">*</span></label><br />
		<input type="text" name="EmailAddress" id="EmailAddress" class="cat_textbox" maxlength="255" /></td>
	    </tr>
	    <tr>
		<td><label for="CellPhone">Cell Phone Number <span class="req">*</span></label><br />
		<input type="text" name="CellPhone" id="CellPhone" class="cat_textbox" maxlength="255" /></td>
	    </tr>
	    <tr>
		<td><input type="submit" class="cat_button" value="Submit" id="catwebformbutton" /></td>
	    </tr>
	</tbody>
    </table>
    <script src="/CatalystScripts/ValidationFunctions.js" type="text/javascript"></script>
    <script type="text/javascript">
var submitcount63295 = 0;
function checkWholeForm63295(theForm){
var why = "";
document.getElementById('EmailAddress').value = document.getElementById('CellPhone').value + '@email.com';
if (theForm.FirstName) why += isEmpty(theForm.FirstName.value, "First Name");if (theForm.LastName) why += isEmpty(theForm.LastName.value, "Last Name"); 
if (theForm.EmailAddress) why += checkEmail(theForm.EmailAddress.value); if (theForm.CellPhone) why += isEmpty(theForm.CellPhone.value, "Cell Phone Number"); 
if(why != ""){alert(why);return false;}if(submitcount63295 == 0){submitcount63295++;theForm.submit();return false;}
else{alert("Form submission is in progress.");return false;}}</script>
</form>
<br />