Valid
	XHTML 1.1! Valid CSS!
Created 20/6/05 Modified 20/6/05
Chelton Evans

Java Script home

Developing jscript
Cookies
Accessing the Documents Elements
Strings
Check Box Example
School Assignment
Misc

Developing jscript

I used Mozilla's Tools>Web Development>Java Script Console. This gives the exact line number where the script is broken. After jscript breaks, from that point on further javascript may well be broken. The javascript is interpreted as the html is interpreted from top to bottom of a web page.

Place as much jscript in js files so it separate from html where possible or isolated.

<head>
...

<script type="text/javascript" src="orders.js"></script>
</head>

This reads in the javascript declarations and possibly executes code. Then later on you can call the javascript functions frow within your html. One way is to use the script imbedding.

<script type="text/javascript"> bannerright(); </script>

The same script tag can be used to imbed javascript directly.

Using the validator also improves your javascript because it tells you when you are using obsolute techniques. I validate with Strict html.

Accessing the Documents Elements

I use a simple mechanism. Give the whatever an id and grab the object through it.

Wrap the input inside a form and give the form no action.

<form id="CustomerDetailsForm" action="javascript:void(0)">

<p>Enter your address. <br/>
Street:   
<input id="AddressStreet" type="text" /><br/>
City:  
<input id="AddressCity" type="text" /> <br/>
Postcode:  
<input id="AddressPostCode" type="text" size="5" />
</p>

To access AddressPostCode, refer to document.getElementById("AddressCity").value . This is a string.

So the variable is accessed in java script by the above call to the document, but how is the java script triggered in the first place?

Here is an example of a button that triggers a jscript function call. The function does everything - its job is to read any data. The only thing the html input does is the trigger. This minimizes the amount of jscript in the html which makes the html easier to manage.

<p>
<input id="Submit" type="button" value="Submit" onclick="OrderSubmit()" />
</p>

Cookies

Cookies can be used in a couple of ways. One cookie for each value, or one cookie has a list of keys with values.

For the simple way of using a cookie, just bake it, access it and delete it. For example if (CookieGet("Target")==null) { ... the cookie does not exist.

Cookies can also be used to keep track of the state. eg redirecting to another page if the state is not good.

/*
http://home.cogeco.ca/~ve3ll/jstutor9.htm
*/

function CookieBake(name,value) {
   argv=arguments;
   argc=arguments.length;
   expires=(argc>2) ? argv[2] : null;
   path=(argc>3) ? argv[3] : null;
   domain=(argc>4) ? argv[4] : null;
   secure=(argc>5) ? argv[5] : false;
   document.cookie=name+"="+escape(value) +
     ((expires === null) ? "" : ("; expires="+expires.toUTCString())) +
     ((path === null) ? "" : ("; path="+path)) +
     ((domain === null) ? "" : ("; domain="+domain)) +
     ((secure === true) ? "; secure" : "");
}

function CookieEat(name) {
   arg=name+"=";
   alen=arg.length;
   clen=document.cookie.length;
   i=0;
   while (i<clen) {
      j=i+alen;
      if (document.cookie.substring(i,j) == arg) {
          return EatCookieVal(j);
          }
      i=document.cookie.indexOf(" ",i) + 1;
      if (i === 0) {break;}
   }
}
function CookieEatVal(offset) {
   endstr=document.cookie.indexOf(";",offset);
   if (endstr == -1) {endstr=document.cookie.length;}
   return unescape(document.cookie.substring(offset,endstr));
}

/* Debuged and fixed this code
 * by looking at the following websited. 
 * http://www.javascriptworld.com/scripts/script12.05.html
 */
function CookieDelete(name) {
  expDate=new Date();
  expDate.setDate(expDate.getDate()-1);
  document.cookie=name+'=;expires='+expDate.toGMTString();
}



/**
 * From http://www.netspade.com/articles/javascript/cookies.xml
 *
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function CookieGet(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

Misc


/*  roundOff function from 
 *  http://javascript.internet.com/calculators/horsepower.html
 */
function roundOff(value, precision) 
{
  value = "" + value;
  precision = parseInt(precision);
  var whole = "" + Math.round(value * Math.pow(10, precision));
  var decPoint = whole.length - precision;
  if(decPoint != 0) 
  {
    result = whole.substring(0, decPoint);
    result += ".";
    result += whole.substring(decPoint, whole.length);
  }
  else
  {
    result = whole;
  };
  return result;
}


/**
 * DHTML email validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */

function echeck(str) 
{
  var at="@";
  var dot=".";
  var lat=str.indexOf(at);
  var lstr=str.length;
  var ldot=str.indexOf(dot);
  if (str.indexOf(at)==-1)
  {
    alert("Invalid E-mail ID");
      return false;
  }

  if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr)
  {
    alert("Invalid E-mail ID");
    return false;
  }

  if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)
  {
    alert("Invalid E-mail ID");
    return false;
  }

  if (str.indexOf(at,(lat+1))!=-1)
  {
    alert("Invalid E-mail ID");
    return false;
  }

  if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)
  {
    alert("Invalid E-mail ID");
    return false;
  }

  if (str.indexOf(dot,(lat+2))==-1)
  {
    alert("Invalid E-mail ID");
    return false;
  }
		
  if (str.indexOf(" ")!=-1)
  {
    alert("Invalid E-mail ID");
    return false;
  }

  return true;
}



function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag)
{   
  var i;
  var returnString = "";
  // Search through string's characters one by one.
  // If character is not in bag, append to returnString.
  for (i = 0; i < s.length; i++)
  {   
    // Check that current character isn't whitespace.
    var c = s.charAt(i);
    if (bag.indexOf(c) == -1) returnString += c;
  }
  return returnString;
}


Strings

A lot of java script does horrific things with strings. Quoting within a string is notorious in Unix and nesting of quotes is at times frustrating.

Here is an example of backslaching or escaping the " character. So you can include it in the one string.

  document.writeln(
"<img src=\"images/contact_off.gif\" id=\"menu05\"  alt=\"contact_off.gif\" /></a>"
  );

This results in the following html.

<img src="images/contact_off.gif" id="menu05"  alt="contact_off.gif" /></a>

Check Box Example

var dvdimgs = new Array();
var dvdtitle = new Array();
var dvdprice = new Array();


var dvdcount=0;
var dvdcurrent=0;

function init()
{
  var i=0;
  
  dvdtitle[i] = "Amusement Park";
  dvdprice[i] = 29.99;
  dvdimgs[i++] = 'images/dvd01s.jpg';

...



function dvdSubTotalcalculate()
{
  dvdsum=0.0;
  dvdCheckBox=document.getElementById("dvdform").dvdCheckBox;
  var i=0;
  for ( ; i<dvdcount; i++)
  {
    if (dvdCheckBox[i].checked)
      dvdsum += dvdprice[i];
  };
  dvdsum = roundOff(dvdsum,2);
}

function dvdorderscheckbox()
{
  document.writeln("<div class=\"float15\">");
  document.writeln("<form id=\"dvdform\" action=\"javascript:void(0)\" >");

  var i=0;
  for ( ; i<dvdcount; i++)
  {
    document.write("<input type=\"checkbox\" id=\"dvdCheckBox\" onclick=\"dvdSubTotalwrite()\" "); 
    document.write(" value=\"\"" + i);
    document.writeln(">" + dvdtitle[i] + " <br/>");
  }
  for ( i=0; i<20; i++)
    document.write("  ");
  document.writeln(" Sub-Total");

  document.writeln("</form>");
  document.writeln("</div>");

  document.writeln("<div class=\"float10\">");
  i=0;
  for ( ; i<dvdcount; i++)
  {
    document.writeln("$" + dvdprice[i] + "<br/>");
  }

  document.writeln("<form id=\"dvdSubTotalCart\" action=\"javascript:void(0)\">");
  document.write("<input type=\"button\" id=\"dvdSubTotalButton\" ");
  document.writeln("value=\"0.0\" onclick=\"dvdSubTotalwrite()\" />");
  document.writeln("</form>");

  document.writeln("</div>");
}