Tutor

HTML:
CSS ASP ASP.NET JavaScript Flash

Beginner link: Beginner HTML
<!-- This line would be a comment line in HTML -->

Special Characters:
 Space &nbsp;
 < &lt;
 > &gt;
 & &amp;



<input type="button" value="A Button">


<select name="select1">
<option selected value=0>Choose</option>
<option value=1>Option #1</option>
<option value=2>Option #2</option>
<option value=3>Option #3</option>
</select>

Choose 10 lbs.
Choose 20 lbs.
Choose 30 lbs.
<input name="howmanypounds" checked value=10 type="radio">Choose 10 lbs.
<input name="howmanypounds" value=20 type="radio">Choose 20 lbs.
<input name="howmanypounds" value=30 type="radio">Choose 30 lbs.


<TEXTAREA NAME=MyTextBox COLS=40 ROWS=5 WRAP=virtual></TEXTAREA>

Click here to see HTML forms in action with JavaScript and ASP

Anchor Tags:
PURPOSE: Hyperlinks that jump to a particular section of a page.
Step #1: Add the #Section to the link.
<a href="samples.asp#javascript">Go to the JavaScript Section</a>
Step #2: Put that #Section into that page where you want to jump to.
<A NAME="javascript">Welcome to the JavaScript Section</a>
Try it: Go to the JavaScript Section

Image links without the ugly border:
<a href="samples.asp" border="0"><img src="../arrow.gif" border="0"></a>
vs

Redirect with HTML:
Withing the head tag...
<meta http-equiv="Refresh" Content="0;URL=http://ivantown.com">

Image Maps:
<img src="pic.gif" USEMAP="#mymap" border="0">

<MAP name="mymap">
<AREA SHAPE="RECT" COORDS="15,15,160,75" HREF="http://yahoo.com">
</MAP>

The first two coords is the upper-left point (x,y) the second two is the lower right corner. A single map can have multiple areas defined.

Cascading Style Sheets (CSS):
CSS ASP ASP.NET JavaScript Flash

Best CSS link: http://www.w3schools.com/css/default.asp
Good CSS link: http://www.blooberry.com/indexdot/css/


<input value="This is normal text.">


<input value="This is bold text." style="font-weight: bold">


<input value="This is bold and comic sans text." style="font-weight: bold; font-family: comic sans ms" size=40>


<input value="Need italic/courier and a background?" style="font-style: italic; font-family: courier; color: white; background: url(http://www.msu.edu/~townivan/wsbg2.jpg)" size=40>


<input type="button" value="w/background and bold" style="background: #ff3600; font-weight: bold">

Grey Input field not using disabled:
<input value=test style="font-weight: lighter; background-color: rgb(216,216,216)" readonly>


Hide and Show with CSS:

<script language="JavaScript">
function showhide(x){
if (document.getElementById("span2").style.display=="block"){
document.getElementById("span2").style.display="none";
}
else{

document.getElementById("span2").style.display="block";
}
}
// end showhide(x)
</script>
<input name="std" value="Hide/Show" onClick="showhide(this.value);" type="button" size="4"><br>
<span id="span2" style="display: none;">
<table bgcolor="#FF0000">
 <tr>
    <td>
This was hidden!</td>
 </tr>
</table>

</span>
Note: You can use "inline" instead of block if you don't want a line break


Active Server Pages (ASP):
CSS ASP ASP.NET JavaScript Flash

Note: ASP is not case sensitive for reserved words and variables.
ASP links: asp101.com 4guys aspin.com asp functions


' This is a comment line in ASP

Concatenation: &
x="part1"
y="part2"
z=x&y
Response.Write(z)
Output: part1part2

Random Numbers:
Randomize(timer) ' using timer as an argument insures a different random number each time.
max=10
min=1
result = Int((max - min + 1) * Rnd + min)
Response.Write(result)

Output: 2
Notes: Click refresh to reload the page and get another random number.

For Loop:
for i = 1 to 10
Response.Write(i & " ")
next
1 2 3 4 5 6 7 8 9 10

While Loop:
i=1
while i < 10
Response.Write(i & " ")
i=i+1
wend
1 2 3 4 5 6 7 8 9

If statement:
if x = 0 then
  response.write("X is really zero!")
else
  response.write("X is definately not zero!")
endif

Switch/Case Statement:
select case aColor
case "red"
   response.write("The color was red!!")
case "green"
   response.write("The color was green!!")
case else
   response.write("The color was neither")
end select


Equality:
= true if equal
<> not equal

Multi-line ASP:
Seperate using the ":" character.
Response.Write("test1"):Response.Write("test2"):Response.Write("test3")
test1test2test3
For line breaks you can encode an HTML <br> code.
Response.Write("test1" & "<br>"):Response.Write("test2"):Response.Write("test3")
test1
test2test3

ASP Include file(works in HTML page also)
<!--#include file="footer.htm"-->

Disable autocomplete:
<FORM AUTOCOMPLETE = "off">
:
</FORM>



TextArea display:
Response.Write Request.Form("Poetry")

However, this will not display the carraige returns and spaces entered by the user in the TEXTAREA. To show the spaces and carraige returns, we will need to use the Replace function. We will begin by reading the value of Request.Form("Poetry") into a string variable- we will then use the Replace functiont twice, once to replace vbCrLfs with
and once to replace spaces with  . Here is the code!

'Read in the value of the TEXTAREA
Dim strPoetry
strPoetry = Request.Form("Poetry")

'Replace all vbCrLf with <BR>s
strPoetry = Replace(strPoetry, vbCrLf, "<BR>")

'Replace all spaces with &nbsp;
strPoetry = Replace(strPoetry, " ", "&nbsp;") 'Output the formatted TEXTAREA value:
Response.Write strPoetry


Some ASP Functions:

String Manipulation:[functions left(), right(),and mid()]
Left(string, # of slots from the left) ex: Left(string1,2) = "Du"
Right(string, # of slots from the right) ex: Right(string1,3) = "One"
Mid(string, Start slot, # of slots to grab) ex: Mid(string1,2,5) = "uckyT"
string1="DuckyTheSillyOne"
x=Left(string1,2)
y=Right(string1,3)
z=Mid(string1,2,5)
response.write (x)
response.write (y)
response.write (z)
Output:
Du
One
uckyT

ABS
PURPOSE: Returns the absolute value of a number
SYNTAX: ABS(number)
ARGUMENTS: "number" is any valid number. If NULL, then NULL is returned; if empty, then 0 is returned.
SAMPLE: response.write ABS(-193.24)
RESULT: 193.24

Array
PURPOSE: Returns an array
SYNTAX: Array(list)
ARGUMENTS: "list" is a comma-delimited list of values to add to the array.
SAMPLE:
Dim X
X = Array("Paul","Mike","Tom")
response.write X(2)

OUTPUT: Tom
COMMENTS: Array index always starts with "0" by default. So the total elements in an array would be UBOUND(ArrayName) + 1

CInt
PURPOSE: Converts a numeric expression to an integer.
SYNTAX: CInt(number)
ARGUMENTS: "number" is any valid number.
SAMPLE: response.write CInt(-97.54)
RESULT: -98
COMMENTS: There is a range limitation for this function: -32,768 to 32,767. If any number beyond this range is passed as argument, run-time error "Overflow" will occur. User INT() function instead.

Date
PURPOSE: Returns the current system date.
SYNTAX: Date
ARGUMENTS: -
SAMPLE: response.write Date
RESULT: 2/23/2012
COMMENTS: Date returned is the SERVER date, not your computer date.

Fix
PURPOSE: Returns the integer part of a number.
SYNTAX: Fix(number)
ARGUMENTS: "number" is any valid number.
SAMPLE: response.write Fix(-97.54)
RESULT: -97
COMMENTS: The difference between Int and Fix is that if number is negative, Int returns the first negative integer less than or equal to number, whereas Fix returns the first negative integer greater than or equal to number. For example, Int converts -8.4 to -9, and Fix converts -8.4 to -8.

FormatCurrency
PURPOSE: Returns an expression formatted as a currency value.
SYNTAX: FormatCurrency(Expression [, Digit [, LeadingDigit [, Paren [, GroupDigit]]]])
ARGUMENTS: "Expression" is a valid numeric expression;
"Digit" is an optional numeric value used to indicate number of digits to the right of the decimal point;
"LeadingDigit" is an optional tristate value to display a leading zero;
"Paren" is an optional tristate value used to display parentheses around negative values;
"GroupDigit" is an option tristate value used to display a number as specified in the group delimiter settings of the Control Panel's regional settings.
SAMPLE: response.write FormatCurrency("843.43294")
RESULT: $843.43

Hour
PURPOSE: Returns a whole number representing the hour of the day between 0 and 23.
SYNTAX: Hour(time)
ARGUMENTS: "time" is any valid date/time expression.
SAMPLE: response.write Hour(Now)
RESULT: 2

Replace
PURPOSE: Returns a string in which a specified sub-string has been replaced with another substring a specified number of times.
SYNTAX: Replace(strToBeSearched, strSearchFor, strReplaceWith [, start [, count [, compare]]])
ARGUMENTS: "strToBeSearched" is a string expression containing a sub-string to be replaced;
"strSearchFor" is the string expression to search for within strToBeSearched;
"strReplaceWith" is the string expression to replace sub-string strSearchFor;
"start" (optional) is the numeric character position to begin search;
"count" (optional) is the number of substrings to be replaced. Default is -1, which means all.
"compare" (optional) is a value indicating the comparision constant
SAMPLE: response.write Replace("This is David.", "David", "John")
RESULT: This is John.

Time
PURPOSE: Returns the current system time.
SYNTAX: Time
ARGUMENTS: -
SAMPLE: response.write Time
RESULT: 2:35:02 AM
COMMENTS: Refresh the page to see the time goes.


Trim
PURPOSE: To remove extra spaces at the beginning or end of a string.
SYNTAX: Trim(string1)
ARGUMENTS: "string1" is any valid string.
SAMPLE:
response.write ("START")
response.write Trim(" Evil spaces are everywhere! ")
response.write ("END")
RESULT: STARTEvil spaces are everywhere!END

Special Character Codes in ASP:
Example: response.write Chr(123)
Output: {

Chr(33) = !
Chr(34) = "
Chr(35) = #
Chr(36) = $
Chr(37) = %
Chr(38) = &
Chr(39) = '
Chr(40) = (
Chr(41) = )
Chr(42) = *
Chr(43) = +
Chr(44) = ,
Chr(47) = /
Chr(58) = :
Chr(59) = ;
Chr(60) = <
Chr(61) = =
Chr(62) = >
Chr(63) = ?
Chr(91) = [
Chr(92) = \
Chr(93) = ]
Chr(94) = ^
Chr(96) = `
Chr(123) = {



JavaScript
CSS ASP ASP.NET JavaScript Flash

Links: JavaScript Source  Another  Regular Expressions for advanced text parsing
Note: JavaScript is case sensitive for reserved words and variables.

Javascript Header:
    Inside of the <head> tags of your html...
    <SCRIPT LANGUAGE="JavaScript">
    function calc(){
    alert("You are in a function!");
    }

    </script>

// This is commented javascript
/*
If you had a lot of stuff to comment then you might want
to use something like this to comment multiple lines at once.
*/

Equality:
== true if equal
!= not equal
=== true if equal & same type
!== not identical

Concatenation uses the "+" sign.
Example:
x="12";
y="8";
z=x+y;
To add use the eval() function to treat the variables as numbers instead of strings.
X: Y:
Z:

function concat(){
x=document.frm1.x.value;
y=document.frm2.y.value;
z=x+y;
document.frm1.z.value=z;
} // end concat function
...
<input type=button value="Concat x+y" onclick="concat();">
Or without using a function...
<input type=button value="Concat x+y" onclick="document.frm1.z.value=document.frm1.x.value+document.frm1.y.value">

In the function change the line to:
z=eval(x) + eval(y);


Simple String Manipulation:
.substring(start_point, end_point)
Usage: TARGET_STRING_VARIABLE.substring(start,end) // starts at zero instead of 1 for the first slot
Try it:
Target:
Name_of_target_input_field.substring( , )
Result:
Here is the code:
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function substringexample(){ // this function is for the .substring example
tempstring=document.frm1.substring1.value;
param1=eval(document.frm1.substring2.value);
param2=eval(document.frm1.substring3.value);
tempresult=tempstring.substring(param1,param2);
document.frm1.substringresult.value=tempresult;
} // end substringexample function
</script>
</HEAD>
...Down in the HTML...
<form name="frm1"><br>
Target: <input name=substring1 value="DuckyTheSillyOne"><br>
Name_of_target_input_field.substring(<input name=substring2 value=0 size=1>,<input name=substring3 value=3 size=1>) <input type=button value="Do it!" onclick="substringexample();"><br>
Result: <input name=substringresult><br>
</form><br>

JavaScript Salary Scrubber:
Salary Scrubber to filter out non-number characters
//make sure salary has no weird characters in it
str=document.form1.LTDsalary.value;
re = /^\$|,/g;
document.form1.LTDsalary.value = str.replace(re, ""); // remove "$" and ","
// end salary scrubber

Enhanced Salary Scrubber: Global function that takes any input field and returns the scrubbed value to it.
function scrub(obj){ // make sure salary has no weird characters in it
thescrubtarget=obj.name; // The name of the input tag that called the function.
thescrubnumber=obj.value;// The value in that tag.
str=thescrubnumber;
re = /^\$|,/g;
eval("document.frm1." + thescrubtarget + ".value = str.replace(re, '')"); // remove "$" and ","
} // end of scrub() function
Usage:
In your HTML add something like the following to your input tag:
<input name="box1" onchange="scrub(this);">

Enhanced Salary Scrubber: Netscape 4.7 and IE
function scrub(input){ //make sure salary has no weird characters in it
thetarget=input.name;
s = input.value;
filteredValues = "$,"; // Characters stripped out
var i;
var returnString = "";
for (i = 0; i < s.length; i++) { // Search through string and append to unfiltered values to returnString.
var c = s.charAt(i);
if (filteredValues.indexOf(c) == -1) returnString += c;
}
eval("document.frm1." + thetarget + ".value = "+returnString); // put the scrubbed value back into the input tag
}

Usage:
In your HTML add something like the following to your input tag:
<input name="box1" onchange="scrub(this);">

String Length:
If a variable is a string you can use VarName.length.


<input type=button value="Show me the length" onclick="showstringlength();">
function showstringlength(){
thestringlen=document.frm1.stringlengthtest.value;
alert('Length is '+ thestringlen.length);
}

Rounding Function:
function roundOff(value, precision) {
  value = "" + value //convert value to string
  precision = parseInt(precision);
  var whole = "" + Math.round(value * Math.pow(10, precision));
  while (whole.length < precision) {
    whole = "0" + whole;
  }
  var decPoint = whole.length - precision;
  if(decPoint != 0) {
    result = whole.substring(0, decPoint);
    result += ".";
    result += whole.substring(decPoint, whole.length);
  }
  else {
    result = "0." + whole;
  }
    return result;
}

Using the rounding function:
temp=eval(document.frm1.field1.value);
temp2=roundOff(temp,3);
document.frm1.field2.value=temp2
so if field1 had a value of 123.45678
after clicking the button which calls this function you get 123.457
Try it:
Input:
Result=roundOff(Input, );
   Answer:

Format a number to Currency (1000 to $1,000) Netscape 4.7 and IE
function formatCurrency(num, centsyesno) {
// the second argument shows cents if 1, if 0 then just dollars num = num.toString().replace(/\$|\,/g,'');
// new: if the second argument is 2 then "no cents" + "no $"
// new: if the second argument is 3 then "yes cents" + "no $"
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+
num.substring(num.length-(4*i+3));
if (centsyesno==0){ return (((sign)?'':'-') + '$' + num ); }
if (centsyesno==1){ return (((sign)?'':'-') + '$' + num + '.' + cents); }
if (centsyesno==2){ return (((sign)?'':'-') + num ); }
if (centsyesno==3){ return (((sign)?'':'-') + num + '.' + cents); }
}


Round to the Next highter thousand ( 12100 -> 1300 ):
Saltemp = eval(document.frm1.AnnualSalary.value)/1000;
Saltemp2 = Math.ceil(Saltemp);
Saltemp3 = Saltemp2*1000;
Salary:  
Result:

Alert:
PURPOSE: Popup a message box. Good for debugging.
alert('test');


Min/Max:
Sample:
Math.min(5,3); gives 3
val1=34;
val2=50;
Math.max(val1,val2);
gives 50

Don't go to the next page unless...:
function checkpage(){
if (genderval==false){
alert("Please select your Gender.");
return false;
}
else
return true;
}
}// end checkpage function
<form name="form1" onSubmit="return checkpage()" action="form2.asp" Method="post">

JavaScript Line Breaks:
use "\n"
Example: alert('First Line\nNow the second line.');


Change the selection of a dropdown:
Use .selectedIndex=X;
Keep in mind that X is not the value of the select box. Zero is the first item, One is the next etc.
<input type=button onclick="document.frm1.javadrop.selectedIndex=2;" value="Try it">



When using dropdowns use onchange to make something happen when you choose something from a dropdown.

Open a link in a new window from a hyperlink:
Use this function:
function linkfunction()
{window.open('http://townivan.brinkster.net/eko/damage.htm','windowname');}
Then in the HTML make the link like:
<a href="javascript:linkfunction();">Popup</a>
Try it

Navigate to another page from a button. (like a hyperlink)
Use this function:
function linkfunction()
{window.navigate('http://www.yahoo.com');}
Then in the HTML make the button like:
<input type=button value="Try it" onclick="javascript:linkfunction();">
or without using a function...
<input type=button value="Try it" onclick="javascript:window.navigate('http://www.yahoo.com');">


Control radio buttons with JavaScript:
Javascript:
<script language=javascript>
function change(){
document.frm1.Dogs[2].checked =true;
}
</script>
HTML:
<form name=frm1>
<input name=Dogs value=1 checked type=radio>Poodle<br>
<input name=Dogs value=2 type=radio>German Shepard<br>
<input name=Dogs value=3 type=radio>Terrier<br>
<input type=button value="Select Terrier" onclick="change();" name=btn1>
</form>

Poodle
German Shepard
Terrier
Notice:
- Since each input tag has the same name you add the Dogs[2] to choose which Dogs button to use. Zero is the first one.
- The values don't change. Dogs[0].value is always 1. Dogs[1].value is always 2.



bgcolor=#cccccc
bgcolor=#DEDEDE
bgcolor=#DFDFDF
bgcolor=#f1f1f1
bgcolor=#efefef


Make an input field readonly
document.form2.box1.readOnly=true;

Text using javascript variables:
<SCRIPT LANGUAGE ="JavaScript">
<!--
document.writeln ("<H3>JavaScript Example</H3>\
<P>This text is generated by a JavaScript. If you can see it, you are using a JavaScript-compatible \
browser or other HTTP client. <\P> \
<P> This section tests whether Search Indexing Robots can follow links \
within SCRIPT tags. It is written using JavaScript document.writeln. \
This is the <A HREF='javascript-links.html'>link</A> to the page \
<tt>www.searchtools.com/tests/javascript/javascript-link.html</tt>\
</P> \
")
// -->
</SCRIPT>

or if you want to show something you declared like... var test=123;
the value of test is <script language="javascript">document.writeln(test)</script>

Which item is selected in a select tag?
Assume your HTML looks like:
<form name="frm1">
<select name="colors">
<option selected value="0">Choose</option>
<option selected value="1">Red</option>
<option selected value="2">Blue</option>
</select>
</form>
With IE it's easy. Document.frm1.colors.value will give you 0, 1, or 2 for whichever item is selected.
However old Netscape won't recognize .value instead use .selectedIndex but remember it always starts at 0 and increments for each item. So if your HTML values are 2,4,6 remember that .selectedIndex will give 0,1,2.

JavaScript "For loop" and Random Numbers:
// for (initial; condition; increment) { statements; }
for (x=1; x<10; x++){
random_num = (1 + Math.floor (Math.random() * 3))
document.frm1.bigbox.value=document.frm1.bigbox.value+(x + ": " + random_num + "\r");
}


Trim Function
function trim(inputString) {
// Removes leading and trailing spaces from the passed string. Also removes
// consecutive spaces and replaces it with one space. If something besides
// a string is passed in (null, custom object, etc.) then return the input.
if (typeof inputString != "string") { return inputString; }
var retValue = inputString;
var ch = retValue.substring(0, 1);
while (ch == " ") { // Check for spaces at the beginning of the string
retValue = retValue.substring(1, retValue.length);
ch = retValue.substring(0, 1);
}
ch = retValue.substring(retValue.length-1, retValue.length);
while (ch == " ") { // Check for spaces at the end of the string
retValue = retValue.substring(0, retValue.length-1);
ch = retValue.substring(retValue.length-1, retValue.length);
}
while (retValue.indexOf(" ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
retValue = retValue.substring(0, retValue.indexOf(" ")) + retValue.substring(retValue.indexOf(" ")+1, retValue.length); // Again, there are two spaces in each of the strings
}
return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function


JavaScript redirect page
<html>
<body bgcolor="#FFFFFF">

<script language="javascript">
<!--

location.replace("http://www.yahoo.com");

-->
</script>

</body>
</html>


JavaSCript Confirm Message (before moving to next screen)
function yesno(){
var answer = confirm ("Submit and Continue?")
if (answer){return true;}
else {return false;}
} // end test()


<form name="frm1" action="page2.asp" method="post" onSubmit="return yesno();">

String Functions

The String object comes with a wide array of methods that very few programmers exploit to their full extent. There are methods for manipulating strings, generating HTML tags and searching within strings.

What is a string?

In the JavaScript language strings are objects in their own right. As in Java, they are not stored as arrays of characters so string manipulation must be done using the built-in constructor and mutator functions. In later versions there is a String constructor and a more formalised idea of what these objects are. At this level however a string is any variable made up of alphanumeric characters but not a number.

For example, some valid strings are "Hello", "Bob", "Bob2", "33", "33.3" but not 33 or 33.3. You will have seen a detailed discussion on converting between strings and numbers in the chapter on Data Types in JavaScript. All strings have a property called length that returns the number of characters in the string.

The most commonly used methods used on string objects are: indexOf(), charAt() and substring(). Because these appear so often in JavaScript programs I will try to explain them in detail below.

indexOf()

This function allows you to determine if and where a string appears in a larger string. It is equivalent in part to strstr and related functions from C and InStr from Visual Basic. This method also has a counterpart lastIndexOf() that searches from the other end of the string.

As the name suggests, the return value indicates the position of the string searched for in the string searched over. If there is no match then the value -1 is returned. Remember that in JavaScript -1 is simply an integer and should not be referred to as a boolean.

var myString = "Have a nice day!"; alert(myString.indexOf("a")); // returns 1 alert(myString.lastIndexOf("a")); // returns 13

Remember that arrays in JavaScript all start from 0. The same goes for string indices so even though "a" is the second character, the return value is 1.

You may be wondering now, how you could find the index of the second occurence of the letter "a"? To do this we have to introduce the second parameter of the function. The second parameter is an integer indicating the position to start searching from in the string.

By combining all these features I can modify the code to find all occurences of the letter "a":

var myString = "Have a nice day!"; var index = myString.indexOf("a"); while (index != -1) { alert(index); index = myString.indexOf("a", index + 1); // start search after last match found }

The index variable is initially set to the first location of "a" (or -1 if there is no match). Each time through the loop we search for another match starting from just after the first match (index + 1). When there are no more matches in myString the search returns -1 and the loop exits.

The output of this is a series of alerts: 1, 5, and 13.

In this example we have only shown that indexOf() can search for single characters. By experimenting you will find that the search parameter can be any character or string.

charAt()

This function returns the character at a given position in the string. It is essentially a special case of the substring() method below but useful in its own right. If you are converting code from C or a similar language then you will be able to replace string[index] with string.charAt(index) when referencing a character.

On place where charAt() is commonly used is to check for illegal characters in a form input. For example an email address should be restricted to letters, numbers, periods and an "@" symbol. We can parse a string one character at a time to enforce this:


<SCRIPT language="JavaScript"> <!-- Hide from older browsers var parsed = true; var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-"; var email = prompt("What is your email address?", "nobody@nowhere.com"); for (var i=0; i < email.length; i++) { var letter = email.charAt(i).toLowerCase(); if (validchars.indexOf(letter) != -1) continue; alert("Invalid character: " + letter); parsed = false; break; } if (parsed) alert("Your email address contains all valid characters."); // Stop hiding --> </SCRIPT>

Working Example

The example above uses a number of string functions as well as a loop and some boolean operators. All of these features have been previously covered individually apart from the toLowerCase() function which is described below.

The method is quite simple, to test each character in the email address against a set of valid characters. However the implementation will seem a bit awkward if you are used to C or Perl programming. Essentially, we loop through the email using charAt() to extract individual characters. We then check to see if each character is valid.

If the character is valid then we continue the loop (jump back to the for statement). If the character is not valid (does not appear in the validchars string) then we display an alert with that character and use break to end the for loop after setting parsed=false.

When the loop exits we check the flag to see if the email has been validated. If parsed is true then a message is displayed. Note that we do not have to test (parsed == true) - this would still work but is unnecessary for boolean variables.

substring()

This function is used to extract any portion of a string. The parameters are 'start' and 'end'. The start value is the index of the first character to return. The end value is the index of the first character after the portion to return. This may seem illogical but an easy way to remember it is that the length of the returned string is end - start.

If the second parameter is omitted then the end point is taken to be the last character in the string.

var str = "This is a string";
str.substring(1, 3); hi
str.substring(3, 1); hi
str.substring(0, 4); This
str.substring(8); a string
str.substring(8, 8);  

The second example in this table demonstrates how the parameters are automatically reversed if start > end. While an interesting feature, this SHOULD NOT be relied on as JavaScript 1.2 will return an out of memory error in such cases. The last example shows that when the start and end are equal, the return value is the empty string.

String Formatting (HTML)

These have got to be some of the least-used functions in JavaScript. While not exceedingly useful they do add a certain panache to your code. These methods create HTML code from string objects for displaying on the page.

str.anchor("anchor1") <A NAME="anchor1">This is a string</A> This is a string
str.big() <BIG>This is a string</BIG> This is a string
str.blink() <BLINK>This is a string</BLINK > This is a string
str.bold() <B>This is a string</B> This is a string
str.fixed() <TT>This is a string</TT> This is a string
str.fontcolor("darkred") <FONT COLOR="darkred">This is a string</FONT> This is a string
str.fontsize(5) <FONT SIZE="5">This is a string</FONT> This is a string
str.italics() <I>This is a string</I> This is a string
str.link("index.html") <A HREF="index.html">This is a string</A> This is a string
str.small() <SMALL>This is a string</SMALL>This is a string
str.strike() <STRIKE>This is a string</STRIKE>This is a string
str.sub() <SUB>This is a string</SUB> This is a string
str.sup() <SUP>This is a string</SUP> This is a string
str.toLowerCase() this is a string this is a string
str.toUpperCase() THIS IS A STRING THIS IS A STRING

The last two examples in the above table are not specifically HTML related but may be useful as formatting tools. All of these methods may be applied in series to a string in order to create a custom format.


<BODY> <SCRIPT language="JavaScript"> <!-- Hide from older browsers var heading = prompt("Please enter a heading", "Test Heading"); var colour = prompt("Please enter a colour", "darkred"); document.write(heading.fontsize(7).fontcolor(colour).bold().toUpperCase()); // Stop hiding --> </SCRIPT> </BODY>
Detecting when a key is pressed:
<script language="JavaScript">
function doSomething(e)
{
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
alert('Character was ' + character);
}
document.onkeypress=doSomething
</script>


JavaScript Date InputString to Object:
function ConvertDateStringToDateObj(StringIn){
var x = StringIn.split('/');
var Objout = new Date(x[2], x[0]*1-1, x[1]);
return Objout;
}// end ConvertDateStringToDateObj(StringIn)

function ConvertDateObjToDateString(ObjIn){
var x = ObjIn.getMonth()*1+1+ "/" + ObjIn.getDate() + "/" + ObjIn.getFullYear();
return x;
}// end ConvertDateStringToDateObj(StringIn)