JavaScript
From Online Business Wiki
Click on + to expand the category
Introduction
What is JavaScript?
JavaScript is a prototype-based scripting language with a syntax loosely based on C programming language. Like C, the language has no input or output constructs of its own. Where C relies on standard I/O libraries, a JavaScript engine relies on a host environment into which it is embedded. There are many such host environment applications, of which the web browser is the best known example. (taken from http://en.wikipedia.org/wiki/Javascript)
Sample Javascript Code
Below you will find some commonly used snippets of Javascript code, that you may find useful when implementing sites on the platform.
Please note that all code samples are provided as a guide only - and may need to be customised for your own application. You will need to be proficient in Javascript implementation, as no support is provided for the implementation of these items
Make username field equal to email field
If you want to make the customer’s email address their secure zone username then you will need to make some slight changes to your web form. In the system the username and the email address fields are different. And for the customer to use their email address to login, their email address must also be stored in the Username field.
You can customize a web form to automatically populate the username fields with the customer’s email address.
To do so follow these steps:
Insert your web form on to a web page Hide (not remove) the username field. You can do this by wrapping it in a HTML div element which is hidden.
e.g.
<div style= display:none;>Username<br><input type=text name="Username" ></div>
Make the email address field automatically update the Username field when an email address is entered.
e.g.
<input type=text name="EmailAddress" onBlur="document.getElementById('Username').value=this.value;>
Assigning a Web App item name to a page title
<script type="text/javascript">
function titlechange()
{
document.title = "{tag_item_name}";
}
</script>
</head>
<body onload="titlechange()">
Redirecting to another page
The following is the example of a JavaScript which will redirect a visitor to various URLs for 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
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>
Script:
<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>
Make billing information same as shipping
This script will populate billing information in the checkout form if the customer selects a "Same as shipping" checkbox.
Here is the code for the checkbox:
<input type="checkbox" onclick="SetBilling(this.checked);"/> Same as Shipping
JavaScript:
<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>
Add email verification field and JavaScript inside a web form
You need to go 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 into the existing JavaScript code:
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 (note that in your code the function name will probably 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 above code to the existing code it should 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
Here is the script you can use in your large or small products layout (place at end):
<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>
If you do this, for every item that is not on sale, the retail price will be hidden.
Dropdown menu for multi-currency websites
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
Return a customer to your default URL from the receipt page
When the customer has made a purchase, if they continue browsing, it will be on your secure URL. If you want to redirect them to your default URL, you can 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>
Return a customer to a different URL based on their country
If you use several domains with different currencies, you can modify the script above to support that. 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';
Show a hidden DIV if customer is logged in
Sometimes you want to hide an element and check if the customer is logged in and if they are you want to display that element. In this case you'd use the {module_isloggedin} module that displays 1 if customer is logged in and 0 if not. So, if you have the following code:
<div id="hiddenform" style="display:none"> ... </div>
This is the script you would use to display that DIV:
var loggedin = "{module_isloggedin}";
if (loggedin == 1)
document.getElementById('hiddenform').style.display = "block";
Replacing Shipping options with custom text
<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
<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, this Javascript needs to be added 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
Note - be careful where you place this - it will supress any alert windows....so if you place it on your site wide templates, it will supress ANY alery popup.
<script type="text/javascript">
window.alert=function(msg){}
</script>
Overriding The "Checkout" Button on the Checkout page
This script would go in Admin->More Customization Options->Online Shop Layouts->Checkout Step
It will essentially allow you to add a javascript function before the checkout submits and goes to 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 "This product is unavailable or out of stock" message
If you wish to change the message that’s shown when the last unit of a product is added to the cart, e.g. it runs out of stock and the system displays "This product is unavailable or out of stock", you need to add the following JavaScript code to your Overall Layout in Admin -> More Customization Options -> Online Shop Layouts or to the site-wide template:
<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 text form fields when a site visitor browses 'back' to a previously submitted form
This script can be useful for security - i.e. if you wish to ensure that a site visitors entries into a web form are not 'viewable' by navigating 'back' to the page after submission. It needs to be placed 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 date format to North American date format
Announcement dates
In announcements you can use {tag_counter} to generate the item ID and to access the date. Then use some JavaScript to re-format the date.
In this example we'll reformat {tag_eventfromdate}, 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}".
Please note that this method is to be used in the list layout. in the detailed layout all you have to do is change the id from id="date{tag_counter} to something else e.g id="dateid".
<span id="date{tag_counter}">{tag_eventfromdate}</span>
Here is the JavaScript that will take that date e.g. 23-Apr-2009 and convert it to something like 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_eventfromdate}";
Literature dates
In literature, same as in announcements, you can use {tag_counter} to generate the item ID and to access the date. Then use some JavaScript to re-format the date.
In this example we'll reformat {tag_expirydate}, 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}".
Please note that this method is to be used in the list layout. in the detailed layout all you have to do is change the id from id="date{tag_counter} to something else e.g id="dateid".
<span id="date{tag_counter}">{tag_expirydate}</span>
Here is the JavaScript that will take that date e.g. 23-Apr-2009 and convert it to something like 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}";
Web App dates
Refreshing the page after adding product to a cart
You will need to place this code in the Site Wide Template that your shopping cart is using (or link to this JAvascript in an external file) -
<script type="text/javascript">
function AddProductExtras(){
document.location.reload(true);
}
</script>
Hiding the red 'x' in IE when you have empty image fields in web app display
In your 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 your web app layout where you have the image displaying, place the following:
<img src="/Utilities/ShowThumbnail.aspx?USM=1&W=75&H=75&R=1&Img={tag_imagename_value}"
OnError="ImageLoadFailed()" class="right" alt="{tag_name_nolink}" />
Capturing form fields in the special instructions box for a product
This code, when used on your large product layout (Admin > More Customisation Options > Online Shop Layouts > Large Product Layout) will take 3x separate input lines of text and combine them into one set of 'special instructions' separated by commas, assuming the product has 'Capture Details' enabled.
It will then add the item to the cart when selecting the image (you will need to substitute a correct path for src="/yourcustomisedbutton.jpg" in the third last line of this code.....)
<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 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 number from the cell number field, attach "@email.com" to it and populate the email field with it. This must be done, because the form can not be submitted without email address.
All that was done here is that the following line was added to the 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 redirect to a custom page by appending &PageID=/landingpage.htm to it.
Form:
<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 />
Removing decimal zeros from the product prices
The price tag normaly renders the price in the following format e.g. $12.00. If you want to remove the .00 from the price and display $12 only, you need to do the followin:
First you need to go to the template your online shop is wrapped into and add the following line to it:
<script language="JavaScript" type="text/javascript" src="/js/jquery-1.3.2.min.js"></script>
Note: you need to download jQuery library from http://docs.jquery.com/Downloading_jQuery and upload it to your site.
You then need to go to Admin -> More Vustomization Options -> Online Shop Layouts -> Overall Layout and paste the following code into the bottom of the page.
<script type="text/javascript">
$('.price').each(function() {
price = $(this).text().replace('.00', '');
$(this).text(price);
});
</script>
The code will strip all .00 and display the price as an integer.

