Javascript Tutorial

Javascript Tutorial #3

In this tutorial, I'll show how the computer can appear to be a bit more intelligent, able to make decisions based on input and modify it's output. This is achieved using the IF statement. I won't be repeating the entire text file as in previous tutorials so you will need to read them first. Here then is a simple IF script:-

var myInput;

myInput=prompt("Please enter your name",'name');
if (myInput=="nick")
{
alert('Hello ' + myInput);
}


As before, two variables are created (using var) ready for use. We use the prompt box as before to get input from the user and store it in MyInput. This is then used by the if (must be lower case) statement to decide wether or not to display the input. Note that myInput uses a single = to assign a value but the if statement uses a double equals to check for equality. As it stands, this is not terribly useful as only the exact user input (in this case the word nick in lower case) will allow the message box to be displayed. It would be more useful if the program could point out to the user the kind of input required if it is wrong. This is where the else statement makes an appearance.

var myInput;

myInput=prompt("Please enter your name",'name');
if (myInput=='nick')
{
alert('Hello ' + myInput);
}
else
{
alert ('Incorrect name ' + myInput + '. Should be nick');
}

Now a message will be displayed no matter what is input. Note that an error condition will still occur even if the word Nick or NIck (or any other upper/lower case mixture) is input. To get around this, use the command toLowerCase. Replace the following line:-

if (myInput=='nick')

with

if (myInput.toLowerCase()=='nick')

This will take the output from the prompt function (in this case a name) and convert it to lower case before doing the comparison. Note that the variable MyInput is unchanged and is thus displayed in the case as typed in the prompt box.

So now it is possible to show you another Dialog box function which will prove useful in the future. It looks like this.

var myInput;

myInput=confirm('Please enter your name');
alert (myInput);

When run, the message box will display the return value of the confirm function which in this case will either be true (if OK pressed) or false (if cancel selected). This can be used as follows.

var myInput;

myInput=confirm('Please enter your name');

if (myInput==true)
{
alert('OK returns ' + myInput);
}
else
{
alert ('Cancel returns ' + myInput);
}

So now, it will be possible to ask the user whether or not to carry out some operation (like overwriting an existing file for example) without resorting to text input but instead using only a single mouse click. Have a play with these programs and see if you can add your own variations. The next tutorial will be a little more taxing than this one as we'll be investigating loops.

Back

Written by Nick Cheesman. Last updated: 01/04/2004
Please eMail me at:
nickjc@nickjc.co.uk