JavaScript

JavaScript is not Java!



In order to properly learn and use JavaScript you should have an understanding of HTML. The more HTML you know the better you will be able to use JavaScript. You can implement JavaScript with a casual knowlege of HTML. JavaScript allows you to create "active" web pages without knowing alot of programming or having access to a CGI bin. HTML is technically not a programming language. HTML pages are "stateless," meaning what you see is what you get and there is no interation. JavaScript, imbeded within HTML, makes web pages user interfaces and portals for sending and receiving data. If you are even remotely familiar with C, Basic or any other programming language, JavaScript will be a snap. When first learning JavaScript the most common mistake is putting the script in the wrong part of the HTML code.

To learn more about HTML, click here

Click this link to see a simple HTML script which you can copy and alter.

A great way to learn HTML is to view the page source of other websites. To do this, right-click in the broswer window and select "View Source."



JavaScript may be placed in the body of a web page, in the header or in a seperate file. When in the BODY or HEAD it should be inside SCRIPT tags and be sure to specify LANGUAGE=JAVASCRIPT since the default language of many browsers is VBScript. Examples:
<HEAD>
<SCRIPT LANGUAGE=JavaScript>
Script goes here
</SCRIPT>
</HEAD>
Or
<BODY>
<SCRIPT LANGUAGE=JavaScript>
Script goes here
</SCRIPT>
</BODY>

To call from a seperate file, place you script in a file with the extension .JS for JavaScript, example: someScript.js. Then, from within an HTML document:
<SCRIPT SRC="someScript.js">
</SCRIPT>
Keep in mind that you must use the exact location of the file here. If it is out on the web somewhere, use the URL:
<SCRIPT SRC="http://www.someSite.com/someScript.js">
</SCRIPT>

Some simple JavaScript scripts

A JavaScript Redirect with a drop-down menu
Click here for the source
JavaScript Alerts
Click here for the source
Some JavaScript Math
Type a number

Added to 2:

Divided by 2:

Times 2:

Subtracted by 2:

Click here for the source

Rounding numbers in JavaScript

POST Versus GET

POST and GET are methods that follow "METHOD=" in the FORM tag. They determine the way data is passed from a form. The main difference between POST and GET methods are that form values are displayed in the URL line if you use a GET and hidden if you use POST. The GET method is useful error checking since the field values are visible. The default value is GET.

Form Using POST

Form Using GET






Playing with HTML Form Values

The point of a web form is to accept values and pass them somewhere else to be processed. There are different types form fields: checkboxes, radio buttons, drop-down lists, comment boxes and text boxes. The fields are created with HTML tags. The tags can have several attributes, depending on the type of field. The most important attibute is "VALUE." For example, if you enter your age as 24 in a field on a form, the VALUE for that field is equal to 24. If the name of that field is "age", "age=24" would be passed from the form.

Change Button
The words displayed on a form action button is a value. The value can be changed. Enter a new button name and click the button.
Button Name

This is done using the built-in JavaScript function onClick. Within the button tag, the value of the button is changed the value of the field.

Copy Field Value
Values may be copied from one form field to another. Enter a value in the first field and click the button.

Field 1:
Field 2:
This is done using the built-in JavaScript function onClick. Within the button tag, the value of the second field is changed the value of the first field.
Click here for the source(s)



Form Validation

Let's face it, people are lazy when they fill-out forms. We have to make sure they fill in all required information, don't put their name where they are supposed to put their phone number, etc.

Leave the fields blank and click "Done"

Name:
Email:
This one only checks to see if there is a value in the field, others can check to see if the value is the right type or format. This form passes the field values to a function which checks to see if they are blank.

Click here for the source



Dealing with radio buttons

Radio buttons: A B C can be a real pain in the neck if you don't understand that they are treated as arrays by functions. The way that radio button values are passed is different from other form input types. For example, if you had this set of three radio buttons:
<INPUT TYPE=RADIO VALUE="a" NAME=q1> A
<INPUT TYPE=RADIO VALUE="b" NAME=q1> B
<INPUT TYPE=RADIO VALUE="c" NAME=q1> C
You might think that you could do this in a function:

if(document.form1.q1.value=="a"){
    alert('You answered A');
}


but you would be wrong. You need to do this:

if(document.form1.q1[0].checked==true){
    alert('You answered A');
}


Technically, all three radio buttons are part of the same piece of input because they are all named "q1". Selecting a radio button option makes it "true", not selecting it makes it "false." Becuase value="a" is the first radio button in the array it is q1[0], value="b" is q1[1], value="c" is q1[2]. Arrays start with zero, the number in the [ ] is called an index.


Adding a value to a form entry

Let's say people enter their user ID on a web page and that the user ID is the same as their email. So to save time you want to add the '@whatever.com' onto the end of the ID they enter.

@whatever.com


Another example would be area codes.
(212)
These both use the onClick method placed in the button tag.
onClick="this.form.fieldname.value=this.form.fieldname.value + 'extra value'"

Specifically:
for the email one: onClick="this.form.userid.value=this.form.userid.value + '@whatever.com'"
for the the area code one: onClick="this.form.phone.value='212-' + this.form.phone.value"


Change one character in a string
This function replaces a "@" with a "." in a string using the charAt() function to determine the chararcter position and then goes through the string baclwards to build the new string. This could be done with a for loop, using var i in the charAt(i) but the literal numbers are used to make it clear.
<SCRIPT LANAGUAGE=JAVASCRIPT>
function insertChar(){
var result;
result = '';
if(document.formName.inputVal.value.charAt(2)=="@"){
result = document.formName.inputVal.value.charAt(5);
result = document.formName.inputVal.value.charAt(4) + result;
result = document.formName.inputVal.value.charAt(3) + result;
result = "." + result;
result = document.formName.inputVal.value.value.charAt(1) + result;
result = document.formName.inputVal.value.value.charAt(0) + result;
alert(result);
}

}//end insertChar
</SCRIPT>
</HEAD>

<BODY>
<FORM NAME=formName onSubmit="return insertChar()">
<INPUT TYPE=TEXT NAME=inputVal>
<INPUT TYPE=SUBMIT>

</FORM>
</BODY>



Add commas to a number
Enter a number with more than 3 digits:
<HTML> <HEAD>
<SCRIPT LANAGUAGE=JavaScript>
function addCommas(){

var newNum = '';
var oldNum = document.numTest.myNumber.value;
var revNum = '';
var revNum2 = '';
var wComm = '';
var cnt = oldNum.length;
for(var i = cnt; i >= 0; i--){
   revNum = revNum + oldNum.charAt(i);
}
newNum = revNum;

var thrd = 0;

if(newNum.length>3){
  for(var j = 0; j < cnt; j++){
    wComm = wComm + newNum.charAt(j);
    thrd++;
    if(thrd%3==0){
      if(j!=cnt-1){
        wComm = wComm + ',';
      }
    }
  }
}

var nCnt = wComm.length;

for(var k = nCnt; k >= 0; k--){
  revNum2 = revNum2 + wComm.charAt(k);
}

alert(revNum2);
}//end addCommas
</SCRIPT> </HEAD>
<BODY> <FORM name=numTest method=post>
<INPUT TYPE=TEXT NAME=myNumber><BR><BR>
<INPUT TYPE=SUBMIT VALUE=SUBMIT onclick="addCommas()">
</FORM>
</BODY>
Reverse a string
The code for reversing a string is part of the code above, here is the for loop that does it:
for(var i = myString.length; i >= 0; i--){
   revString = revString + myString.charAt(i);
}



Hide/UnHide Form Fields
This can actually be used to hide or reveal any section of an HTML page, but I usually use to hide "extra" input fields on a form in case a user might need them. This uses the HTML DIV tag to mark sections.
<HEAD>
<script language ="javascript">
function unHider()
{
document.all.div1.style.display = 'block';
document.all.div2.style.display = 'none';
}
function hider()
{
document.all.div1.style.display = 'none';
document.all.div2.style.display = 'block';
}
</script>
</HEAD>
<BODY>
<div id="div2" STYLE="display: block">
<input type="button" name="moreF" value="More Fields" onClick="unHider();">
</div>
<div id="div1" STYLE="display: none">
<INPUT TYPE=text>
<input type="button" name="moreF" value="Remove Fields" onClick="hider();">
</div>
Important: the DIV tag might not work in Netscape.
Page Redirects
This is great for forwarding users to a new page or site when the old one has been moved.
Put this in the HEAD portion of the HTML between SCRIPT tags(SCRIPT LANGUAGE=JavaScript) to send users to a new site:
function redirect(){ window.location = "http://www.newsite.com" }
Then, inside the BODY tag: OnLoad="redirect()"
OR

To simply a new page:
function redirect(){ window.location = "newpage.html" }
Then, inside the BODY tag: OnLoad="redirect()"
Whatever you do, don't set a page to redirect to itself.

Auto-submit
You may have a form auto-submit based on an entry in a field, a selection from a drop-down list, a checkbox being checked, etc...

Place this in the HEAD of your HTML between SCRIPT tags:
function autoSubmit(){
     document.form.submit();
}
Then place some code inside the from input tags to trigger the function(remember, this will work if you form is called "form," if it has another name put that name in the function):
OnClick="autoSubmit()" or OnBlur="autoSubmit()"
Assigning values to variables
A variable is a kind of placeholder for values you want to use. In JavaScript, use the keyword var to create variables(or "declare" variables). Examples:
var myNum
myNum = 12

var myStr
myStr = "Hello!"

Generate HTML with document.write
Use document.write to create HTML content within SCRIPT tags. This:
document.write("<H4>Hello</H4>");
document.write("This is from JavaScript<BR>");
Would produce this:

Also to create custom content based on variables. This:
var myName = "Fred";
document.write("My Name is: ");
document.write(myName);
Would produce this:
Note that literals are in quotes, variables are unquoted.

Functions and return values

In general a function is a seperate section of code that manipulates data sent to it and then returns it to the main program. Functions in JavaScript can be identified by the keyword function followed by a function name of your choosing. Try and use function names tha describe what the function does. Example:
function times12(x){
    return x * 12;
}
The prceeding function is called times12, accepts some value "x" and then returns that value that value multiplied by 12. A function is kind of like a restauran kitchen. A waiter delivers an order on paper to the kitchen. The kitchen returns a cooked meal to the waiter for delivery to the customer. The waiter does not know or need to know what goes on in the kitchen, and neither does the customer.
To call this from somewhere, use code like this:
document.write(times12(5));
If properly coded, "60" should be printed as 5 is sent to times12() and then returned. Or, something like this:
var myNum;
myNum = times12(5);



Built-in Functions

JavaScript comes with many great functions that can be called from within your scripts

Events occur when something happens on a page or form

onSubmit calls an event or function when a form is submitted. This is very uselful for validation since onSubmit can call a function which checks form values and return false if the form is not formatted properly which keeps the form from submitting. onSubmit is usually placed within the FORM tag or within the tag for the SUBMIT button. It is used with the = sign. Example:
<FORM NAME=myForm onSubmit="return isValid()">

onClick is similar to onSubmit but can be used on any INPUT field when the field is clicked on. This could be a button, checkbox, etc. Example:
<INPUT TYPE=BUTTON VALUE="Click Me" onClick="alert('You clicked a button');">

onBlur oddly named, it calls an action or function when a user moves away from an input field. Example:
<INPUT TYPE=TEXT SIZE=50 VALUE="Click here, move away and click somewhere else" onBlur="alert('You moved away');">

onChange works like it looks like it might, when you change an input value it calls an action or function. Example:
Un-check this box then click somewhere.
<INPUT TYPE=CHECKBOX onChange="alert('You unchecked this');" CHECKED>

onLoad put in inside the BODY tag to call a function when the page is loaded.

onFocus is the oposite of onBlur, it is called when an input area receives the cursor.

<INPUT TYPE=TEXT VALUE="onFocus test here" onFocus="alert('Cursor is here');">

String functions test or modify passed values

length will tell how many characters are in a string.
var mySize = myString.length

charAt() isolates a single charater in a string.
var firstChar = myString.charAt(0)





Form Tips

Making a Form: A practical demo
Date functions
Prevent Submission with ENTER key
confirm()
Prevent mutliple submission




JavaScript Resources

Server-side JavaScript Reference
JavaScript Toolbox
javascript.internet.com Free code, tutorials, links.
javascript.com Free code, tutorials, links.
Web Monkey JavaScript
JavaScript Guide
Rounding numbers in JavaScript
Dr. Dobb's Source Code