Java Script Basics

What is Java Script? For our purposes, Java Script is an interpretive computer language designed to be run by Web browsers for the purpose of adding extra functionality to Web pages. Unlike a normal programming language, Java Script is not compiled and turned into an executable program (.EXE) or class file. Instead, it is embeded as part of an HTML web page, then downloaded and executed by the browser. Java Script itself looks like a mixture of HTML code and Java code. You should use Javascript  to verify user input on web forms before the form is sent to the server.  This removes load from the server and gives a prompt response to users when they make mistakes. Important note:  since Java script is executed by the browser  your Javascript may behave differently on various browsers. You'll need to test your pages on Internet Explorer, FireFox, Chrome, and Safari (and probably others).

Some good tutorials and information can be found at:

As a beginner, you should think about JavaScript as being composed of :

Format of code:
var x = 3;
var y = 4.0;
var s =  "My Name";
Some useful JavaScript funtions:
alert("the message to show");
answer = confirm("Do you want to continue?");

          answer = prompt("Question","Default answer");
         answer = Math.pow(2,3);  // raise 2 to the 3
var i = parseInt("123");
var f = parseFloat("123.22");

Note: parseFloat and parseInt do not generate exceptions, instead they return NaN as a value
         var f = 33.456678;
         var s = f.toFixed(3);    // limit to 3 decimals,  s = 33.457
isNaN("123");

Note:  isNaN will return false for empty strings in some browsers,  therefore to do a complete test you need to check from an empty string as well, e.g.

if(isNaN(number.value) || number.value="")
{
     // error
}

window.print();
document.write("add this to the document");


Using document.write to create common headers/trailers for web pages.
Creating JavaScript Functions (methods):
<HEAD>
<script TYPE="text/javascript">
<!--
  //
  // add x to y and return the result
  //
   function add(x, y)
    {
       return x+y;
     }
// -->
</script>
</HEAD>


Accessing HTML form fields from within functions:
<FORM NAME ="nameForm" METHOD=POST ACTION = "url">
Last Name: <INPUT TYPE=TEXT NAME= "lastName" SIZE = 20> <br>
First Name: <INPUT TYPE=TEXT NAME= "firstName" SIZE = 20>
<INPUT TYPE =SUBMIT NAME="submitButton" VALUE="SUBMIT">
</form>

document.nameForm.lastName.value  refers to the text typed in the last name box
document.nameForm.firstName.value  refers to the text typed in the first name box

with(document.nameForm)
{
    var lname = lastName.value;
          alert("your last name is "+lname);
    var fname = firstName.value;
          alert("your first name is "+fname);
}
lastName.value = "Flintstone";
lastname.style.color = "red";  //  text color is now red
lastname.style.background = "yellow";  // background is yellow
lastname.style.borderColor = "red"; // red background

if(lastname.value == "")
      {
       valid = false;
       message = message + "last name cannot be blank\n";
       lastname.style.borderColor= "red";
       lastname.style.borderWidth = 4;
      }
      else
     {
        lastname.style.borderColor = "black";
        lastname.style.borderWidth = 2;
      }

JavaScript Events:
Creating simple calculators
<script TYPE="text/javascript">
//
// Add X to Y, place result in Answer
//
function add()
{
  with(document.calculator)
  {
    if(isNaN(x.value)) // check x
    {
      x.style.color = "red";
      alert('X must be a valid number');
      return;
    }
    else
     x.style.color = "black";

    if(isNaN(y.value))  // check y
    {
      y.style.color = "red";
      alert('Y must be a valid number');
      return;
    }
    else
     y.style.color = "black";

    var numx = parseFloat(x.value);  // convert x to a number
    var numy= parseFloat(y.value);  // convert y to a number
    var numz = numx+numy;           // add the numbers together

    answer.value = numz.toFixed(3);  // store answer with 3 decimal places
    return;
  }
}
</script>



Validating forms:

<HTML>
<HEAD>

<SCRIPT TYPE="text/javascript">
<!--
  function checkForm()
  {
    var valid = true;
    var message = "Errors: \n";

    with(document.surveyForm)
    {
     if(name.value == "")
     {
       valid = false;
       message = message + "name field is blank\n";
     }
     if(street.value == "")
     {
       valid = false;
       message = message + "street field is blank\n";
     }
     if(city.value == "")
     {
       valid = false;
       message = message + "city field is blank\n";
     }
     if(state.value == "" || state.value.length != 2)
     {
       valid = false;
       message = message + "state field is invalid\n";
     }
     if(zip.value == "" || isNaN(zip.value))
     {
       valid = false;
       message = message + 'zip field is invalid\n';
     }
     if(email.value == "")
     {
       valid = false;
       message = message + "email field is blank";
     }

    }



    if(!valid)
      alert(message);
    return valid;

  }

// -->
</SCRIPT>
</HEAD>
<BODY>

<H2>Information Request Form </H2>

<P><B><I>Please enter all information so that we can better help you!</I></B></P>

<P><FORM METHOD="POST" ACTION="mailto:junk@nowhere.com" NAME = "surveyForm"
     onSubmit = "return checkForm()"></P>

<TABLE>
<TR>
<TD>Name:</TD>

<TD><INPUT type="text" name="name" size=20 maxlength=30></TD>
</TR>

<TR>
<TD>Street Address :</TD>

<TD><INPUT type="text" name="street" size=20 maxlength=30></TD>
</TR>

<TR>
<TD>City:</TD>

<TD><INPUT type="text" name="city" size=20 maxlength=30></TD>
</TR>

<TR>
<TD>State:</TD>

<TD><INPUT type="text" name="state" size=3 maxlength=2></TD>
</TR>

<TR>
<TD>Zip:</TD>

<TD><INPUT type="text" name="zip" size=15 maxlength=15></TD>
</TR>

<TR>
<TD>Email Address:</TD>

<TD><INPUT type="text" name="email" size=30 maxlength=40></TD>
</TR>
</TABLE>

<P>Have you ever purchased from us before? <INPUT type="checkbox" name="customer" value="yes"></P>

<P><BR>
Pet Type :&nbsp;&nbsp;&nbsp;
           <INPUT type="radio" name="PetType" Value="Cat"> Cat &nbsp;&nbsp;&nbsp;
           <INPUT type="radio" name="PetType" Value="Dog" Checked> Dog &nbsp;&nbsp;&nbsp;
           <INPUT type="radio" name="PetType" Value="Bird"> Bird &nbsp;&nbsp;&nbsp;
           <INPUT type="radio" name="PetType" Value="Reptile"> Reptile &nbsp;&nbsp;&nbsp;
           <INPUT type="radio" name="PetType" Value="Fish"> Tropical Fish  </P>

<P>Products you are interested in :</P>

<UL>
<P><SELECT NAME="Products" Size=4 MULTIPLE>
   <OPTION Value="Pet Food">Pet Food
   <OPTION VALUE="Collars/Leashes">Collars and Leashes
   <OPTION VALUE="Medications">Medications
   <OPTION VALUE="Treats">Treats
   <OPTION VALUE="BOOKS">Books and Literature
   <OPTION VALUE="Cages">Cages
   <OPTION VALUE="Aquariums">Aquariums and supplies
</SELECT></P>
</UL>

<P>Enter questions or further information here:</P>

<P><TEXTAREA NAME="INFO Request" Rows=4 Cols=50>enter your questions here</TEXTAREA></P>

<P>
 <INPUT type="Submit" Name="action" Value="send">
 <INPUT type="reset" Value="clear">

</FORM>

</BODY>
</HTML>

Calculator Example

<HTML>
<HEAD>
<SCRIPT TYPE="text/javascript">
<!--

function addXY()
{
  with(document.calculator)
  {
    if(xfield.value.length == 0 || yfield.value.length == 0)
    {
        alert("X and Y cannot be blank");
        return;
    }
    if(isNaN(xfield.value) || isNaN(yfield.value))
    {
      alert("Invalid value for x or y");
      return;
    }

     var x = parseFloat(xfield.value);
     var y = parseFloat(yfield.value);
     var z = x + y;

     answerfield.value = z.toFixed(3);

  }

}

-->

</script>
<title>Calculator</title>
</HEAD>
<BODY>

<form name = "calculator">
X: <input type = "text" name = "xfield" size = 20><br>
Y: <input type = "text" name = "yfield" size = 20> <br>
answer: <input type = "text" name = "answerfield" size= 20><br>
<input type="button" value = "Add" onClick="addXY()">

</form>

</BODY>
</HTML>