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">
<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:
This was hidden!
<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
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"-->
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
strPoetry = Replace(strPoetry, " ", " ") '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:
{
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.
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 Confirm Message (before moving to next screen)
function yesno(){
var answer = confirm ("Submit and Continue?")
if (answer){return true;}
else {return false;}
} // end test()
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:
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.
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.
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)