Web Design/Getting to know the Document Object Model with JavaScript

From Wikiversity
Jump to navigation Jump to search
Web Design Getting to know the Document Object Model with JavaScript
This page is part of the Web Design project.

The Document Object[edit | edit source]

So far we've been playing with the Window object... This has allowed us to do things like open new windows, close old windows, bring up 'alert' boxes (window.open(), window.close(), window.alert() respectively).

But the window object isn't the only useful object around! Using your new-found JavaScript awareness, see if you can find out what the 'document' object is used for! You might want to check your JavaScript Cheat Sheet or a W3Schools tutorial...

Finding out what's on our document[edit | edit source]

Open up a form that you've created and do the following:

  1. Choose a simple Text field on your form, and give it an id="firstname"
  2. Add an 'onsubmit' event to your form tag, and write the code as follows: onsubmit="window.alert('The value is ' + document.getElementById('firstname').value);"
  3. Now test out your form by typing in your field then clicking submit!


What's happening when I click submit?

  1. The browser checks whether there's an onsubmit event on the form
  2. The browser breaks down the onsubmit JavaScript into these pieces:
    1. Search through the entire document for an element with an ID of 'firstname'
    2. Get the text typed into the 'firstname' element (the value of the text field)
    3. Display the value in an alert box

This kind of code is extremely common, especially the document.getElementById() bit. Let's find out how it works.


A short description of document.getElementById()

When we give a tag an ID, it gives the browser a way to specifically identify the tag over all the other <input>s, <p>s or <div>s on the page. We'll often write CSS that targets an ID (eg. #firstname { color: blue }) and the browser hunts down the tag by its ID to apply the style. JavaScript's document.getElementById() is similar, except that we can do a lot more with it afterward than just styling.

When we write code like

  document.getElementById("firstname")

the browser gives us back a 'reference' to the tag (referred to as an element in JS). We can access (and change) almost every aspect of the element including its attributes, styling, position in the document, or even its ID. For example,

  document.getElementById("firstname").type = 'checkbox';

would find 'firstname', then change its type to 'checkbox' (instantly turning your text field into a checkbox!).

These properties (such as 'type', 'value', 'style', 'tagName' and 'className') all belong to the element, and are part of the Document Object Model that describes how the browser sees and works with your page.

Creating functions in Javascript[edit | edit source]

We've got a problem now... it would be great to do a lot more than just one window.alert() when the user submits their form. In fact, we need to do a lot more. For this reason, we'll need to create our own function in JavaScript.

To do this, add the following code somewhere inside your <head>...</head> tags:

<script type="text/javascript">
	  
  function checkForm()
  {
    window.alert('The value is ' + document.getElementById('firstname').value);	  
  }
</script>

Now we can modify our form's onsubmit to just call our new function, checkForm().

  <form action="mailto:me@myfakeemail.com" onsubmit="checkForm()" >
  ... all your other form elements go here ...
  </form>

Give it a try... it should behave exactly like it did before, but now we'll be ready to add more statements to our program!

Input Validation in JavaScript[edit | edit source]

Now that we've tested our function to see that it works, we now want to change it so that it will actually test the value of our field to see if it's empty, and if it is, then let the user know! To do this, we'll need to use an if-else statement.

<script type="text/javascript">
	  
  function checkForm()
  {
		  
    if (document.getElementById("fullname").value == "")
    {
      window.alert("Please enter your fullname");
    }
	  
    else if (document.getElementById("address").value == "")
    {
      window.alert("Please enter your address");
    }
	  
  }
</script>

Our JavaScript code isn't perfect yet, but it's a good start!

Have a go at building on this to check the rest of your form's input boxes (Note: only the input boxes for the moment, don't worry about radio buttons or check boxes or the like). You might also want to learn more about the if-else statement at w3schools.

More on Functions[edit | edit source]

Before we can finish off our input validation, we need to learn a little more about JavaScript Functions. It would be worth reading w3schools JS Functions page right now to find out a bit more about how functions work.

In particular, take notice of how functions can return a value... spend some time playing with the W3Schools Try It Interactive Demo for Javascript functions.

Try the following:

  1. modify the demo so that multiplies 4 and 5 instead of 4 and 3.
  2. modify the product function so that it adds the two numbers instead of multiplying them.

Stopping your form from being submitted[edit | edit source]

When you test your form, you'll notice that even though your input validation picks up the fact that there's stuff missing, it still goes ahead and tries to submit the form! We need to stop our form from being submitted if the input validation fails (ie, if the user has left some required field blank!)

Luckily for us, our form's onsubmit event controls this! If the JavaScript code that is run on our onsubmit event evaluates to 'false', then the browser won't submit the form. Make the following modification to your onsubmit event:

  <form action="mailto:me@myfakeemail.com" onsubmit="return checkForm();">
    ... all your other form elements are here ...
  </form>

Now all you have to figure out is where you can put the JavaScript statement:

  return false;

in your checkForm() function. In plain English, if you can figure out at which points your if-else statement should say "OK! The input validation failed, don't let the form be submitted!", then that's where your return false should go. Give it a try!

You might also need to have a situation where your checkForm() function has this bit of code:

  return true;

Step through your checkForm() code mentally, and see if you can find the point where you can say: "OK! Everything was entered correctly on the form, let it be submitted!" If you can find this spot, that's where you want to return the value 'true'.

Putting the Focus back in the field[edit | edit source]

Wouldn't it be nice to put the cursor back into the right spot for our user after we have just asked them to enter their name? For example, the user didn't fill in their fullname, so when they tried to submit the form, our input validation pops up saying "Please enter your fullname". We already know how to get our hands on an object for the fullname input element using the document object's getElementById() method (see above code), but we don't have any idea how we can get this to put the cursor back in this input field (this is called: receiving the focus).

Have a look at W3Schools JavaScript HTML DOM Reference and see if you can find the reference for our input text field.

When you find the right reference (the one that corresponds to our text input box), scroll down to take a look at the methods for this object, and you will find that it has a built-in focus() method! Click on the focus() method and look at the example you find there.

Can you figure out whereabouts you will need to put this code (with a small modification) in your own checkForm() function? Have a go... and if you get stuck, ask for help! (Hint: we want to put the focus on our fullname field right after we alert the user to the fact that they haven't entered their full name!)

Copy-n-paste-n-edit this so that it works for the rest of your input validation fields too.

More advanced Input Validation techniques[edit | edit source]