Chapter 3 : Processing on the Front End JavaScript Technically its name is ECMA-262, which refers to the international standard which defines it. The standard is derived mostly from Netscape's JavaScript, but it does have some features from Microsoft's JScript. Its most common use (by far) is to provide scripting support for Web browsers. All of the popular "modern" Web browsers support the core standard.
<!-- JavaScript statements //--> Scripts are included in HTML files by placing them inside an HTML script container inside either the head or body section of the document. The HTML comment markers are to hide the JavaScript statements from older browsers that don't understand the HTML script element. JavaScript statements are executed in document order as the Web page is first being loaded into the browser. See firstprogram.html See fragmentedscript.html
JavaScript is loosely typed, which means a variable can hold any of JavaScript's literal types: var x=3.14; // number x="a string";// string x=true;// Boolean The keyword var is used to declare variables since no typing is required. There are some special fixed literal values. It's better to assign predefined literals when weird things happen than to crash Web browsers! var y;// uninitialized variables are // assigned the literal undefined var y ="yi"*"kes"; // y contains NaN // Not a Number y = 3/0; // y contains the literal Infinity
The basic syntax is very similar to that of Java and C++. The operators are standard.
The concatenation operator is +. x="3"; y="4"; z=x+y;// "34" a=y+x;// "43" But + is also used for addition of numbers. x=3; y=4; z=x+y; // 7 This duality is a problem since most data stored in HTML form elements is string data. We can parseFloat() (or parseInt() ) data to force addition. x="3"; y="4"; z= parseFloat(x)+parseFloat(y);// 7
Conditionals are standard: Loops are standard:
The syntax for functions is standard, with the exception that you don't declare types for parameters or for returned values. Here is an example of a void (no return value) style function. function customrule(width,char) { for (var x=1 ; x<=width ; x++) { document.write(char); } document.write(" "); } Here is a sample call to the function. customrule(25,"#"); Here is the result in the Web page. #########################
Here is an example of a return style function. function times10(num) { num=num*10; return num; } Here is a sample call to the function. var num = times10(3); The result is that the variable num contains 30. Scope in functions is straight-forward and works as you would expect. Global variables are visible inside functions. Function parameters are local to the function call and so are variables declared inside functions using the var keyword. Primitive variables are passed to functions by value. Objects are passed to functions by reference.
Scope example: function scopedemo(x) { var y=10; x++; y=x+y; z++; } var x=2; var y=3; var z=4; scopedemo(z); Result: After the function call, the state of the global variables are x 2, y 3, z 5 Note that global variables "live" so long as the page is loaded into the browser. Refreshing the page, re-initializes global variables. Local variables "live" only during the function call.
Arrays are also standard with the exception that you don't need to define what type(s) it may hold. Create a new array object. var list=new Array(); Initialize some array cells. list[0]="hello"; list[1]=3.14; list[1000]=true; The allowed indices are not pre-determined, but it's best to stick to standard array indexing, unlike the above example which skips some indices. Array variables are objects. JavaScript doesn't yet support classes and inheritance, but there are several built in classes with constructors (like Array() ) which are available.
Our main focus here is to use JavaScript to process HTML forms. Forms are created using only HTML. Form Buttons
Text Form Elements
Option Form Elements See bigform.html
Part of the Browser Object Many aspects of a Web page can be changed by changing the Browser Object using JavaScript. This statement will change the text color of the page to red. window.document.fgColor="#0000FF";
Here, we are mostly concerned with form objects. A form is an object. Its name is reference to the object. Form elements are properties of the form object. Again, the name of the element is the reference to the object. A text field is a string object. It's data is in its value property. document.fred.textbox.value The button's onclick event handler calls a JavaScript function named f(). The function changes the content of the text field. The change in the Web page is immediate. function f() { document.fred.textbox.value = "there"; } See formobject.html
Event Handlers (listeners) are special properties of the various objects. Common Examples: ObjectEvent Handlers window onfocus, onblur document onload, onunload link onclick,onmouseover,onmouseout form buttononclick An event handler can be placed as an attribute in the HTML element which creates the object. These examples call the built-in JavaScript alert() function when the event happens. click me See loadevents.html See linkevents.html
We will mostly create custom functions to handle user events. These functions will primarily access, and perhaps change, the elements (hence the data) in form object. The data is in a form element's properties, which are standard variable types. Form ElementIts Fundamental Data Type(s) text field, text areastring - the data radio button, checkboxBoolean - is it checked? string - the data menu (single)number - which option is selected array of strings - the data for each option menu (multiple)array of Boolean - is a given option checked? array of strings - the data for each option
The form of Figure 3.9 and a diagram to represent the object. The branches show object references. The primitive variables are listed at the ends of branches
Below is the same form as previous slide All form elements are indexed by a built-in elements[] array. This is useful when you need to iterate over several form elements. You can use either this array or the name given to the form element for object reference.
Client-side processing of data in HTML forms: Text field -- a string with no new line characters Text area -- a string potentially with new line characters Note: These form elements are incapable of holding numeric data. For example, If you assign a numeric literal to a text element in the Browser Object, it is converted on the fly into a string.
See calculator.html
Processing user choices: Checkbox -- Boolean Variable Hidden string data Radio Button -- Boolean Variable Hidden string data Note: There is no built-in way to test which one(s) are checked from among a group. The best way is to loop over them and test each one.
See cart.html
Menus Single selection -- Works like a single selection group of radio buttons. Note: selectedIndex property of the menu holds the currently selected menu index -- no need to iterate to find user's choice. Multiple selection -- Works like a group of checkboxes. Note: selectedIndex property of the menu only holds the first (usually) currently selected menu index -- have to iterate over the selected properties of the menu options to find all the user's choices. See cartax.html
Validation Before Submission to Server <form name="formname" method="GET" action=" ">... document.formname.onsubmit=verify; // has to be after def. of submit button function verify() { -return true if form data is ok -return false otherwise -- form won't be submitted } See menuverify.html See cart2.html
Validation using string object: var str = "Scooby Doo"; // automatically treated as a string object So for example, var x=str.charAt(1); Causes the variable x to contain the string "c" Using various methods of a string object, you can extract any information you want about the string.
Summary of the String object: If you have worked with strings before, most of this already should be familiar to you in concept.
Example: Verify the following about the form below. The name must be at least 4 characters long, must contain at least one blank space, and must neither begin nor end with a space. The address must be at least 5 characters long, must contain no blank spaces, must contain exactly character, and must contain at least one period. The zip code must be numeric and exactly five characters long. See textverify.html