JavaScript Fundmentals

General Notes, Basic syntax, Functions, Form Validation, Debugging Skills

General Notes on JavaScript

Basic Syntax

The following introduces basic syntax of javaScript language, namely, variables, operators and control structures.

JavaScript Variables

  • Variable names are case sensitive
  • Variables must be begin with a letter or the underscore character
  • With JavaScript, to create a local variable, you precede the variable declaration with var.
  • You do not specify a type when the variable is declared
  • Example declarations are:
    var myInt=20;	//integer
    var myString="hello there"; //string
    var stringQuote='the "string"'; //string
    stringQuote='Tom\'s house';
    sum=myInt + 2;

    // OR you can define in one line:
    var myInt=20, myString="hello there", stringQuote='the "string"';

JavaScript Operators

  • Using "=" to assign values.
    y=5;
    z=2;
    x=y+z;
    
  • Basic arithmetic operators.
    x=y+2; // Addition
    x=y-2; // Subtraction
    x=y*2; // Multiplication
    x=y/2; // Division
    x=y%2; // Modulus (division remainder)
    x=++y; // Increment, or x=y++;
    x=--y; // Decrement, or x=y--;
    
  • Using "+" to concatnate strings or add text values.
    var first_name = "Steve";
    var last_name = "Jobs";
    var name = first_name + " " + last_name; 
    //the person's name is "Steve Jobs"
    
    var hello = "Hello" + 7; 
    //the value of hello is "Hello7"
    
  • Comparison operators.
    var x = 5;
    x==8;    //is equal to, return false
    x==5;    //return true
    x==="5"; //is exactly equal to (value and type), return false
    x!=8;    //is not equal, return true
    x!=="5"; //is not equal (neither value or type), return true
    x>8;  //is greater than, return false
    x<8;  //is less than, return true
    x>=8; //is greater than or equal to, return false
    x<=8; //is less than or equal to, return true
    
  • Logical operators.
    var x = 6, y=3;
    (x < 10 && y > 1) is true // and
    (x==5 || y==5) is false // or
    !(x==y) is true // not
    
  • Note: an empty string, "", is not null
    var car="";
    //if car is null or car is an empty string
    car==null || car=="" // false || true, return true
    
    //if car is not null and car is not an empty string
    car!=null || car!="" //true || false, return true, wrong condition.
    car!=null && car!="" //true && false, return false, correct condition.
    

Control Structures

  • The if ... else statement.
    var time=new Date().getHours();
    if (time<10){
      x="Good morning";
    }
    else if (time<20){
      x="Good day";
    }
    else{
      x="Good evening";
    }
    
  • The for loop.
    for (i=0;i<10;i++){
      if (i==3){
        break;
      }
      x=x + "The number is " + i + "<br />";
    }
    
  • The while and do-while loop.
    while (i<5){
      x=x + "The number is " + i + "
    "; i++; } // or use the do-while loop do{ x=x + "The number is " + i + "
    "; i++; } while (i<5);

JavaScript Functions

The following introduces javascript function related topics, including, definition of functions, javascript events and popup boxes.

Functions

  • Usually, JavaScript functions are defined in the <head> part of the HTML page.
  • The key word function is used to declare a function. The keyword should be written in lower case.
  • The following shows an example function that invoke a Alert Box:
    <!DOCTYPE html>
    <html>
    <head>
    <script type="text/javascript">
        	function AFunction()
        	{
    		 alert("<p>Hello CS215!</p>");
        	}
    </script>
    </head>
    <body>
    	<button onclick="AFunction()">Try it</button>
    </body>
    </html>
  • A function with arguments:
    <!DOCTYPE html>
    <html>
    <head>
    <script type="text/javascript">
    function myFunction(name,job)
    {
    alert("Welcome " + name + ", the " + job);
    }
    </script>
    </head>
    <body>
    
    <button onclick= "myFunction('Harry Potter','Wizard') ">Click for Harry Potter</button>
    <button onclick= "myFunction('Bob','Builder') ">Click for Bob</button>
    
    </body>
    </html>
    
  • Function with a return value:
    <!DOCTYPE html>
    <html>
    <head>
    <script type="text/javascript">
      		function myFunction(){
      			return "Hello World";
      		}
    </script>
    </head>
    <body>
    
    <button onclick= "alert(myFunction()) ">Click for Harry Potter</button>
    
    </body>
    </html>  	
      	

Events

Events are things that the user does (or things that happen to the page) that can trigger JavaScript to do something. JavaScript has a series of event handlers, for instance, if the user clicks on a button, the onclick event handler will take note of the event and will do what it was assigned to do. The following provides a list of some of the event handlers. For a more comprehensive list see http://www.w3schools.com/jsref/jsref_events.asp:

  • onclick
  • onload
  • onunload
  • onmouseover
  • onmouseout
  • onfocus
  • onblur
  • onchange

You will sometimes see code like the following.
<input type="button" value="open" onclick="winmsg()" />
When you click on the "open" button, the winmsg() function will be called.

Popup Boxes

Popup Boxes Firefox Display and Returns Code
Alert Box alert box alert("Alert Message")
Confirm Box confirmBox3 confirm("Confirm Something")
Prompt Box promptbox3 prompt("Ask for Input", "default")

Form Validation

We usually do the client-side validation before sending the content (user inputs) to the server. That is, a JavaScript function will be called for form validation when clicking the "submit" button. Following are examples mainly taken from W3Schools website.

Validating Text Input

The function below checks if a field has been left empty. If the field is blank, an alert box alerts a message, the function returns false, and the form will not be submitted:

function validateForm(){
	var x=document.forms.myForm.fname.value;
	if (x==null || x==""){
  		alert("First name must be filled out");
  		return false;
	}
}

The HTML code are as follow:

	<form name="myForm" action="" onsubmit="return validateForm()" 
        method="post">
	First name: <input type="text" name="fname">
	<input type="submit" value="Submit">
	</form>

Validating Radio Button Input

The HTML code:

<input type ="radio" name= "gender" value="Female"/>Female
<input type ="radio" name= "gender" value="Male"/>Male

The JS code for validation radio button:


var  gender = document.forms.myForm.gender;
var  gen_val = "";

for (var i=0; i < gender.length;i++){
    if (gender[i].checked){
      gen_val=gender[i].value;
      break;
    }
  }
  if(i>=gender.length)
  {
    warn +="Please select the gender: \n";
    rt= false;
  }
  else{
    str_user_inputs +="Gender: "+gen_val+"\n";
  }

Validating Drop-Down List

There are multiple solutions to validate a Drop-Down List. The following provides one solution from www.codeproject.com.

Using selectedIndex Attribute

The JS code:

  
var dplst_e = document.forms.myForm.nationality;

var s_index = dplst_e.selectedIndex;

//  Obtain the value of the selected option
var strUser = dplst_e.options[s_index].value;

// Comparison value 
if(s_index==0)
{ 
                
  warn +="Please select nationality: \n";
  rt = false;

}

else{

    str_user_inputs +="Nationality: "+strUser+"\n";

  }

Validating Checkbox Input

An example to validate the Checkbox (Radio Button):

The HTML code:

	<form name="myForm"  onsubmit="return validateForm()" 
        method="post">
	First name: <input type="text" name="fname">
	Medical History: <input type="checkbox" name="med_chk" value="smallpox" >Smallpox
	<input type="checkbox" name="med_chk" value="mumps" >Mumps
	<input type="checkbox" name="med_chk" value="dizziness" >Dizziness
	<input type="checkbox" name="med_chk" value="sneezing" >Sneezing
	<input type="submit" value="Submit">
	</form>

The JS code for validation:


  var med = document.forms.myForm.med_chk;

  //validate checkbox 

  for (var i=0;i < med.length;i++){
    if (med[i].checked){
      break;
    }
  }
  if(i>=med.length)
  {
   warn +="Medical History \n";
   rt = false;
  }


  else {//if pass validation, then collect user choices

         
   str_user_inputs +="Medical History: ";
   for (var j=0; j < med.length; j++){
     
	if (med[j].checked){
        	
		str_user_inputs +=med[j].value+" ";
       	}//if
   }//for

   str_user_inputs +="\n";
  }//else


Basic JavaScript Debugging Skills

Following content comes from JavaScript Debugging for Beginners

"Development environments are usually nice enough to give programmers a bunch of tools to help determine where their program's going wrong. But with JavaScript, your development environment is a web browser, and things aren't quite so hospitable.". The debugging of JavaScript is especially difficult because:

To make your code easier to debug:

There are several ways to locate JavaScript errors:

  1. Comment out pieces of your code that you think might be producing the error.
  2. Use a log() function to narrate what is happening with your code. You can download this function by clicking here.
    An example of using log() function:
    function countTo (number){
       var target = document.getElementById('counter');
       log('starting countTo');
       if (number > 1){
         log('number is too small to count to');
         return;
       }
       for (var i = 1; i <= number; i++){
         log('count is ' + i);
         target.innerHtml += i + '... ';
       }
    }
    
    The log() function will show you what's going on when executingJavaScript:
    starting countTo
    
    number is too small to count to
    
  3. Using console.log() method, which requires your browser's debugger window. The following link provides more details of JavaScript debugging.
    http://www.w3schools.com/js/js_debugging.asp.

Using Firebug during Developing a Web Project

Firebug provides a powerful JavaScript debugger, CSS and HTML.

Firebug on Linux Machines (in CL115)

You need to check the installation of firebug on linux machines in CL115. FireBug should be installed on CL115 machines already. To active or de-active it, press F12 key.

Debugging JavaScript

To debug the script page, you can use the keyboard short-cuts: F12 (show/hide) or Ctrl+F12. If you use the latter, you will see following script panel: (to set a break point you can left click on the left part of a line number, e.g., line number 70) in the following screenshot:

pic2

Script Panel "The main purpose of the script panel is to debug JavaScript code. Therefore the script panel integrates a powerful debugging tool based on features like different kinds of breakpoints, step-by-step execution of scripts, a display for the variable stack, watch expressions and more."

When you click a button, you will trigger the onclick event, and the javascript function will handle this event. Firebug will execute this function and stop at the break point (the statement with a breakpoint is to be executed).

pic3

You can examine and investigate (watch) variables, stacks in the window at the left side. Also, it is possiable to add a new expression by click and type in the javascript statement.

Step by step debugging: You may use the debugging controls to locate bugs in your JavaScript. Following table provides detials of the control buttons:

pic4

In Class Exercise Lab Assignment

You have completed an HTML medical form in lab1. A task of this assignment is validating user inputs for the medical form by using external JavaScript. The validation of medical form has the following requirements. We assume all inputs are in English. The validation should satisfy the following rules:

  1. Create a new HTML page, js_form.html.
  2. Using external JavaScript to do the validation, for example, create a validate_form.js file.
  3. No empty input. All form elements should have an input.
  4. Exception for rule one: If you choose "No" for "Current Medication", the textarea for "Current Medication" must be empty. Otherwise, there should be an input to indicate the details, i.e., if you choose "Yes", the textarea should not be empty.
  5. Maximun input characters of "First name" or "Last name" are 50 characters.
  6. Maximun input characters of "Address" are 300 characters.
  7. For correct user inputs, show the user inputs in an alert window. Othersiwse, warn the user in an alert window.
  8. Link your js_form.html on the index.html, Please name the link lab4 JS form
  9. zip js_form.html and validate_form.js, upload on URcourses by 11:55 PM.

Note: Output all warnings in one Alert Box, as well as the final result of user inputs. Otherwise, partial marks will be deducted. Using Alert Box is a simple way to give feedback, it is not preferred. The preferred method will actually be discussed in the following lab (i.e., JavaScript and DOM Operations). You should not use alert boxes or other modal windows beyond this lab assignment.