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:
 
<html><head>
<SCRIPT LANGUAGE=JavaScript>
  function confirm(file)  start of function
  {
    var answer = confirm('Are You Sure?');
    if(answer)
        top.location = file;
    return answer;
  }  end of function
</SCRIPT>
</head><body>
<A onClick="confirm('loan.html')">  function call
  For Example:</A>
</body></html>

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:
<html><head>
<SCRIPT LANGUAGE=JavaScript>
  function stringDate() function to get date
  {
   var t = new Date(), mon;
   var day=t.getDate(), yr=t.getFullYear();
   switch(t.getMonth())
   { case 0: mon = 'January'; break;
     ...
     case 11: mon = 'December';
   }
   return mon + ' ' + day + ', ' + yr; return
  }                                 formatted date
</SCRIPT></head><body>
<script>  calling script (write needs to be here)
  document.write("<h1>"+stringDate()+</h1>");
</script></body></html>

Forms


  • 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:

<FORM NAME="frmInput" METHOD="POST"
ACTION="MAILTO:me@myserver.com"> 

  • 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 "MAILTO:me@myserver.com" denotes this is a mailable form and the data sent to me@myserver.com.

Form Elements

Tag Description Appearance
in Form
<INPUT TYPE="text"  
 NAME="txt1" SIZE="10">
Single line textbox 
<TEXTAREA NAME="txtInfo" 
 ROWS=2 COLS=8> </TEXTAREA> 
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 
<INPUT TYPE="radio" CHECKED 
 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" 
 SIZE=2>
  <OPTION>Choice 1
  <OPTION>Choice 2
</SELECT>
Pull down list
<INPUT TYPE="button" 
 NAME="cmdCalc" 
 VALUE="Calculate">
Command Button
<INPUT TYPE="submit"
 VALUE="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:
Excellent!
Okay, I guess...
Keep your day job!
Describe yourself
Suggestions for improving the class?
Shorter Lecture   More Tutorials
Easy Assignments     Longer Break
Comments:

 
<FORM ACTION="mailto:jcarey@asu.edu"
       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">
</TR> 
<TR>
  <TD>Email Address:Another textbox 
  <TD><INPUT TYPE="text" NAME="txtEmail" SIZE="30">
</TR> 
<TR>                 // HTML label that spans 2 columns
  <TD colspan="2">Rate ISM 411 so far...
</TR> 
<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>
<TR> // All radio buttons have the same name
  <TD ALIGN="right"> 
  <INPUT TYPE="radio" NAME="optRate" VALUE="2">
  <TD>Okay, I guess...
</TR> 
<TR>       // All radio buttons have different values
  <TD ALIGN="right">
  <INPUT TYPE="radio" NAME="optRate" VALUE="3">
  <TD>Keep your day job!
</TR> 
<TR>
  <TD>Describe yourself
  <TD><SELECT NAME="lstDesc">Size not given so
      <OPTION>Overachiever           Pull Down Box
      <OPTION SELECTED>OK Student
      <OPTION>Lazy Slug
      </SELECT> End Pull Down Box
</TR> 
<TR>
  <TD colspan="2">Suggestions for improving 
                  the class?2 column label
</TR> 
<TR>
  <TD align="right">Shorter Lecture 
    <INPUT TYPE="checkbox" NAME="chk1">
  <TD>More Tutorials 
    <INPUT TYPE="checkbox" NAME="chk2">
</TR>  // checkboxes have different names
<tr>
  <TD align="right">Easy Assignments 
    <INPUT TYPE="checkbox" NAME="chk3">
  <TD>Longer Break 
    <INPUT TYPE="checkbox" NAME="chk4">
</TR>                // checkboxes have no value
<TR>
  <TD colspan="2">Comments:
</TR>
<TR>
  <TD colspan="2"><TEXTAREA NAME="suggest"
  ROWS="5" COLS="60">
</TEXTAREA>Text Area spans 2 cols & 60 char wide
</TR> 
<TR>
  <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:

    txtH=ISM+411+Rating+Form&txtName=Jane+Doe&
    txtEmail=jane.doe@yahoo.com&optRate=1&
    lstDesc=Lazy+Slug&chk1=on&chk4=on&suggest=None
  • 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:
        alert(frmTest.txt1.value)
    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) 
     {
        alert(form.txt2.value)
     }
    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) 
     {
        alert(form.elements[3].value)
     }
    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)    
     {
        alert(element.value)
     }
  • 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:

Resume:

Here is the code that generates the form above:

<HTML> <HEAD> </HEAD> 
<BODY>
 
<SCRIPT> LANGUAGE="JavaScript">
 
<!--
 
function valid(form) 
{
 
if (form.age.checked) //Checkbox is checked
  {
   
if (form.job.value == "" ||
         form.resume.value == "")

    {
       alert(
"You must complete the form!"); 
      
return false;
    }
   
else
//All fields are completed
  
  {
       alert("Thank your for your resume."); 
       return
true;
    }
  }
 
  else
 
  {
  
  alert("Try again when you are 18."); 
    return
false; 
  }
 
}
// -->  
</SCRIPT>
 
<FORM METHOD="POST"  
      ACTION="mailto:you@yourdomain.com"
      ENCTYPE="text/plain"  
      onSubmit="return valid(this)">  
Your age:<BR>
<INPUT TYPE="
checkbox" NAME="age"><BR>
Desired Job:<BR>
<INPUT TYPE="text" NAME="job" SIZE="40"><BR>
Resume:<BR>
<TEXTAREA NAME="resume" COLS="40" ROWS="5">
</TEXTAREA><BR> 
<INPUT TYPE="submit" VALUE="Send Resume"
</FORM> 
</BODY> 
</HTML>