Javascript-Lesson 4
More choices
switch
The 'switch' statement enables you to make a choice between a number of different values of a variable and execute different blocks for each value. It goes something like this:
switch (n)
{
case 1: // i.e n = 1
execute code block 1
break;
case 2: // i.e. n = 2
execute code block 2
break;
default;
code to be executed if n has a value
that is neither 1 or 2
}
Popup Boxes
Alert Boxes
An alert box is used when you want the user to click 'OK' to proceed. The code is:
alert("text to elicit the 'OK' response");
Confirm Boxes
If the user is to be offered a choice of 'OK' or 'Cancel', then the confirm box is for you:
confirm("text to elicit the 'OK' or the 'cancel' response");
Prompt Boxes
If an even greater response is required from the user, a prompt box is called for:
prompt("text to elicit the response","default value");
Functions
Introduction
Although a Javascript function can be put anywhere on a web page, it is almost completely impractical to put anywhere but in the 'head'. A function can be used to prevent code from executing when the page loads. It is possible to feed the function with variable values from the rest of the script and to return values to the rest of the script. This means that a function can used more than once in a script without the need to repeat the code,
Like variable names, function names may not be reserved words.
Function variables
Variables declared within a function are local variables and can not be used outside the function in which they are declared.