Software, Systems, and Solutions

"We do not run your business. We make your business run better."

Skip Repetitive Navigational Links

JavaScript: Functions

Modular Programming

  • Functions break large tasks into smaller units.
  • They hide details of processing from other parts of the program that don't need to know about them.
  • Functions give rise to modular code. That is:
    • Clear
    • Independent
    • Easy-to-change, easy-to-debug
    • Reusable

Functions and Methods

  • Modules in JavaScript are called functions and methods.
  • A function is any stand-alone piece of code that can accept arguments and can return a value.
  • A method is a function that is associated with an "Object."  In JavaScript the object can be the browser window, the document, an Array, a String etc.

Function Definition

  • Function definitions are distinct; i.e., one cannot define a function within another function.
function function-name(argumentlist)
   // body of the function

function sample1(a,b)
  return a+b;

Invoking Functions & Methods

  • All functions are invoked from other functions or scripts.
  • Calling Function/Script : The location from which another function is invoked.
  • Called Function : The function that is invoked.
  • Function Call : The event of calling a function.
For Example:
  function confirm(file)  start of function
    var answer = confirm('Are You Sure?');
        top.location = file;
    return answer;
  }  end of function
<A onClick="confirm('loan.html')">  function call
  For Example:</A>

Communication Between Functions

  • Through Arguments
    • A calling script may pass values to the called function so that these values can be used by the called function.
  • By a Value returned by a function
    • A return statement with an optional expression is a mechanism for returning a value from the called function to the calling script. The calling script may use this value.
  • Via External variables
    • External variables are globally accessible. They are an alternative to arguments and returned values for communicating between functions.
    • Note : External variables are convenient because they eliminate long argument lists. But they should be used with caution, because they lead to programs with too many data connections between functions.
  • Example Function w/ return, Call from a Script:
  function stringDate() function to get date
   var t = new Date(), mon;
   var day=t.getDate(), yr=t.getFullYear();
   { case 0: mon = 'January'; break;
     case 11: mon = 'December';
   return mon + ' ' + day + ', ' + yr; return
  }                                 formatted date
<script>  calling script (write needs to be here)


  • Web forms are used either to return information to a Web server for some action or to submit information to a local client function (JavaScript or VBScript).
  • The form starts with a <form> tag and ends with </form>. Here's what it looks like:


  • The NAME attribute specifies the forms internal identifier within the Web page (It is similar to the NAME property in Visual Basic).
  • Forms can have METHOD="POST" or METHOD="GET" attributes
  • The ACTION attribute indicates the action taken when the form is completed.  In this case "" denotes this is a mailable form and the data sent to

Form Elements

Tag Description Appearance
in Form
<INPUT TYPE="text"  
 NAME="txt1" SIZE="10">
Single line textbox 
Scrollable text input area
<INPUT TYPE="hidden" 
 NAME="txtH" VALUE="t">
Hidden textbox (not displayed). 
<INPUT TYPE="password" 
 NAME="txtPW" SIZE="10">
Password input box 
 NAME="optGd" VALUE="A">
<INPUT TYPE="radio" 
 NAME="optGd" VALUE="B">
Radio button (only 1 is ON at a time)
<INPUT TYPE="checkbox" 
 NAME="chkPt1" VALUE="1">
<INPUT TYPE="checkbox" 
 NAME="chkPt2" VALUE="2">
Checkbox (more than one can be ON)
<SELECT NAME="lstJunk" 
  <OPTION>Choice 1
  <OPTION>Choice 2
Pull down list
<INPUT TYPE="button" 
Command Button
<INPUT TYPE="submit"
Button to submit form
<INPUT TYPE="reset"> Button to reset form
  • The <INPUT> tag is used to create a new Input box, hidden field, password box, check box, radio button, command button, submit button or reset button.
    • The TYPE attribute of the <INPUT> tag determines the type of input control that is being created.
    • The NAME attribute specifies the fields internal identifier within the Web Page.
    • The VALUE attribute specifies the control's current or default value. 
  • Two additional types of form element tags are TEXTAREA which has ROWS and COLS and SELECT which has a SIZE attribute that specifies how many items to show.
  • Sample Form (in a table): 
Your Name:
Email Address:
Rate ISM 411 at ASU West so far:
Okay, I guess...
Keep your day job!
Describe yourself
Suggestions for improving the class?
Shorter Lecture   More Tutorials
Easy Assignments     Longer Break

       METHOD="POST" NAME="frmRating">
<input TYPE="hidden" NAME="txtH" 
       VALUE="ISM 411 Rating Form">
<CENTER><TABLE WIDTH="80%">Start table centered &
<TR>                        covering 80 % of the window
  <TD>Your Name:HTML text labels the textbox
  <TD><INPUT TYPE="text" NAME="txtName" SIZE="30">
  <TD>Email Address:Another textbox 
  <TD><INPUT TYPE="text" NAME="txtEmail" SIZE="30">
<TR>                 // HTML label that spans 2 columns
  <TD colspan="2">Rate ISM 411 so far...
<TR>  // A set of radio buttons with button in left column 
  <TD ALIGN="right">
  <INPUT TYPE="radio" NAME="optRate" VALUE="1">
  <TD>Excellent!radio's  HTML label in the right column
<TR> // All radio buttons have the same name
  <TD ALIGN="right"> 
  <INPUT TYPE="radio" NAME="optRate" VALUE="2">
  <TD>Okay, I guess...
<TR>       // All radio buttons have different values
  <TD ALIGN="right">
  <INPUT TYPE="radio" NAME="optRate" VALUE="3">
  <TD>Keep your day job!
  <TD>Describe yourself
  <TD><SELECT NAME="lstDesc">Size not given so
      <OPTION>Overachiever           Pull Down Box
      <OPTION>Lazy Slug
      </SELECT> End Pull Down Box
  <TD colspan="2">Suggestions for improving 
                  the class?2 column label
  <TD align="right">Shorter Lecture 
    <INPUT TYPE="checkbox" NAME="chk1">
  <TD>More Tutorials 
    <INPUT TYPE="checkbox" NAME="chk2">
</TR>  // checkboxes have different names
  <TD align="right">Easy Assignments 
    <INPUT TYPE="checkbox" NAME="chk3">
  <TD>Longer Break 
    <INPUT TYPE="checkbox" NAME="chk4">
</TR>                // checkboxes have no value
  <TD colspan="2">Comments:
  <TD colspan="2"><TEXTAREA NAME="suggest"
  ROWS="5" COLS="60">
</TEXTAREA>Text Area spans 2 cols & 60 char wide
  <TD ALIGN="center" colspan="2">
  <INPUT TYPE="Submit"> <INPUT TYPE="Reset">
<TR> // Submit & Reset buttons
</TABLE></CENTER>End Table and centering
</FORM>End Form (MUST include this end tag!)
  • When the Email is received the data will look something like this:

  • If you do not give the form elements a name then what ever is in them will not be mailed!

Referencing Form Fields in JavaScript Programs

  • You can capture data from form elements for use in JavaScript programs in several ways.
  • You can reference individual form elements explicitly by name:
    will display the text in the text box named txt1 found on the form named frmTest
  • You can pass a form to a function and then reference individual form elements explicitly by name:
      <form onsubmit="gettxt2(this)">
     function gettxt2(form) 
    will display the text in the text box named txt1 found on any form that calls the function named getData and passes itself to the form (this) 
  • The individual elements on the form can also be referenced using array notation (like a control array in Visual Basic)
      <input type=text onblur="getelements3(this.form)">   

     function getelements3(form) 
    will display the value of the first element on any form that calls the function named getData and passes itself to the form (this)
  • You can pass an individual form element to a function:
    <INPUT TYPE="text" onBlur="checkInput(this)">
     function checkInput(element)    
  • To use values from a textbox in mathematical calculations you must convert the text to a number using parseInt, parseFloat, parseDouble:

    function calc(elm)   
      var num parseFloat(elem.value);
      alert("square: " + num*num);
  • JavaScript Note: Since JavaScript is case sensitive the names you use in your code MUST exactly match the names in the NAME attribute in the element tag! 

JavaScript for Form Validation

  • Suppose you have a Web site that solicits applicants for their resume and you want to check that applicants are over 18 and validate that all inputs are complete before sending it:
Over 18?:
Desired Job:


Here is the code that generates the form above:

function valid(form) 
if (form.age.checked) //Checkbox is checked
if (form.job.value == "" ||
         form.resume.value == "")

"You must complete the form!"); 
return false;
//All fields are completed
       alert("Thank your for your resume."); 
  alert("Try again when you are 18."); 
// -->  
      onSubmit="return valid(this)">  
Your age:<BR>
checkbox" NAME="age"><BR>
Desired Job:<BR>
<INPUT TYPE="text" NAME="job" SIZE="40"><BR>
<TEXTAREA NAME="resume" COLS="40" ROWS="5">
<INPUT TYPE="submit" VALUE="Send Resume"