Using JavaScript to check the password

Now we’ve built the basic HTML structure of our page, we need to write some JavaScript that will check if the password the user enters is correct.

If they enter the password GabbaGabbaHey they will be taken to the secretinfo.html page.

If they enter an incorrect password an alert will pop up telling them they have got the password wrong.

The first thing we need to do is create a function that will contain all the code we need to check our password.

Let’s create the function inside our < head >. You can put JavaScript anywhere in an HTML web page, and having it in our < head > in this example makes our code easier to understand.

Don’t forget to put your JavaScript inside the < script > tag, like this:

 function checkPassword() {

We then need to create variables that store the value of our password, so that our function can check if the user has got it correct.

Let’s look at the two variables we need:

 function checkPassword() {
 var password = document.getElementById("passwordBox"); //variable 1
 var passwordEntered = password.value; //variable 2

In our first variable, we are using a new built-in function called getElementById. You will learn all about this function and use it more soon.

It is a handy function that finds the HTML element with the specified id attribute. The id attribute we have selected here is for our < input/ > tag.

So the value of our variable will be whatever data the user has typed into the password box.

We then create a second variable to store the data that the user has typed into the password box.

We create this value by typing the name of our first variable followed by a dot (.) then the value keyword.

We do this so we can write an if statement using the value of this variable. We now need to create an if statement.

If the condition of our second variable is true and our password text is equal to (==) GabbaGabbaHey, the hyperlink will work.

If the condition of our variable is false and the password text is not equal to GabbaGabbaHey, the link won’t work and an alert will pop up.

We don’t need to use an else statement because the return statement will halt the function.