code icon

CSCI 1720

Intermediate Web

jQuery II

  1. On your working drive, create a new folder inside your labs folder and name it jquery-2
  1. Download, save it to your jquery-2 folder, and extract the files
  1. Create a new file in the jquery-2/js folder and name it validator.js
  1. Enter a comment block with appropriate comments
screen shot
Fig. 1- Comment block
  1. Add the jQuery $(document).ready() method
screen shot
Fig. 2- $(document).ready()
  1. Let's pause for a moment and see what we've got. Select the index.html file in Brackets and click 'Live Preview'
screen shot
Fig. 3- HTML form: Meh


I don't know if it's just me, or if this is common practice. But when I'm doing a project like this, I usually do it in HTML, CSS, JS order. In other words, I like to get it looking the way I want it before adding the functionality. There's a lot of tweaking that goes on along the way, but let's get our CSS started before returning to the jQuery

  1. You've been provided with a CSS file, main.css that already has a few rules. What we want to do here is style the form, the form buttons, and a modal that we'll use for user feedback. So start by completing the comment block. Then add
screen shot
Fig. 4- Styling the form

Ask yourself: What does this do?

  1. Now add
screen shot
Fig. 5- Styling the contact form's buttons

If you look back at the HTML, you'll see that the Submit and Reset buttons both have their class set to .contactForm-buttons

By now, you should be able to read through each property/value rule and visualize what it will do when displayed. By applying these rules to the class, we ensure that the buttons will both appear the same

  1. Now add
screen shot
Fig. 6- Adding hover effect to buttons
  1. Now add some CSS to style the input fields
screen shot
Fig. 7- Styling the input fields

Here we see that we can select an HTML element by specifying one of its attributes and its value. These rules will only apply to input fields whose type is 'text.' This will make the field a little bigger and add some padding

  1. Since the text in the form fields is now bigger, the labels for the fields probably should be, too
screen shot
Fig. 8- Styling the labels

Since this is a simple form, with only two labels, we can get away with this general rule. In more complex forms, you'll have to use class definitions to make labels for different types of form elements display appropriately

  1. Add the following to style the modal. Notice that we're using the element's ID to select it, instead of a class. Your line numbers may not match up with mine, but that's ok - I just captured the line numbers so I can use them to explain the code below
screen shot
Fig. 9- Styling the modal

So this will create a modal that acts as a dialog box to provide feedback to the user:

  1. Line 60 hides the modal when the page loads
  2. Lines 61-64 positions the modal in the middle of the display
  3. Lines 65-71 are pretty obvious
  4. Line 72 layers the modal on top of the page
  1. Style the modal's 'ok' button
screen shot
Fig. 10- Styling the modal's 'ok' button
screen shot
Fig. 11- ok:hover
  1. That takes care of our CSS for this project. View your page in the browser to see how it looks
screen shot
Fig. 12- contactForm


  1. Now that the form looks the way we want, we need to add its functional behavior. Return to validator.js in Brackets

Let's think about the functionality that we are going to want to add

  1. Both fields should be filled out before it is submitted
  2. The email field should be a properly formatted email address
  3. If 1 and/or 2 are incorrect, the user should be notified and the form not submitted. The user should then be returned to the form to correct the input
  4. Once the fields are properly entered, the user should be notified that the form was successfully submitted

In Project Management, these are called 'functional requirements.' They would be specified, much like you see above, in the project's design documents

  1. We'll need an event listener that will fire when the user clicks the Submit button. In validator.js, add
screen shot
Fig. 13- Event listener for the submit button
  1. Add variables to capture the form input and check for empty values
screen shot
Fig. 14- Check for empty fields

Notice here that we're calling a function called displayError(), which we will define in a moment. This will display the form's modal with an error message. The return  false statement will return the user to the form without submitting it

Lines 16 & 17 use the jQuery .val() method to select the field elements' values and chain it with the .trim() method, in case the user adds spaces after (or before) the input. For some reason, I often hit the space bar after entering something in a form, without thinking about it. Trim will take care of that

  1. Now we need to check the email address that the user enters and make sure it is formatted properly (note that this doesn't check if it is an actual email address, just that its format is correct)
screen shot
Fig. 15- Checking email address format

Note that this block of code also calls another function, isEmail(), which we'll be creating

  1. If the form input passes these three tests, everything is valid. The user will then be advised using the modal
screen shot
Fig. 16- Success message

Notice Line 41. When the page loads, the modal has no content. So after we add the message, success or error, we have to provide a way for the user to close the modal. The jQuery .append() method will add HTML content to an element. In this example, we're dynamically adding a button to the modal. This is going to require some special handling, as we'll see, because the button was added after the page loaded. The .append() method is also used in the displayError() function we're about to create

  1. After the event listener code, add the displayError() function:
screen shot
Fig. 17- displayError()
  1. We need another event listener to close the modal
screen shot
Fig. 18- Close the modal

Here's where the 'special handling' part comes into play. When a page loads, the Javascript files are run. So an element that isn't present when the page loads won't be recognized if it is added later. If we were to try

$('#ok').on('click', function() { ... });

The browser would throw an error - when the page loads - because it wouldn't be able to find the 'ok' id.

We can fix this by making the event fire when the document is clicked. The second parameter in the function call on line 65, '#ok', will make the browser select the named element when the event listener fires, instead of looking for it when the page loads. This allows us to add elements dynamically and interact with them later

So now we can use the 'ok' button to close the modal, even though it wasn't a part of the document when it loaded

Regular Expressions

In order to ensure that the email address the user enters is formatted correctly, we're going to use a Regular Expression. If you're not familiar with RegEx, it is a powerful pattern matching language (or, a kind of 'sub-language') that is included in most, if not all, modern programming languages

RegEx will compare a string or substring to a defined pattern and indicate if the string matches the pattern

All email addresses follow a pattern like this: {id}@{domain_name}.{top_level_domain}. Each of these elements can include certain characters, but not others. For example, the {id} part can have a combination of anything from the letters a to z and A to Z (case matters), dashes (-), dots (.), and/or underscores (_). Any other character is invalid. So if we define a pattern including all of the valid characters, RegEx will return true if the submitted string contains only those characters and false if it contains any invalid characters

This is a thumbnail description of RegEx which I hope will help us complete this assignment. For more information about RegEx, check

  1. The full regex for checking an email address in JavaScript looks like this:
screen shot
Fig. 19- RegEx for email addresses

Now, I don't know about you, but my head almost exploded the first time I saw this.

Over the years, I've learned that when constructing a regex, it's often easier to break it down into smaller components that are easier to understand and then combining the components into the full expression. That's what I've done here

screen shot
Fig. 20- Building a regular expression
  1. Add the code from Figure 20 (or Figure 21, below) to validator.js
screen shot
Fig. 21- function isEmail()

Regex patterns in JS are defined between '/' characters, i.e., /regex_pattern/. The caret (^) symbol specifies the beginning of the string; the dollar sign ($), the end. So /^regex_pattern$/ will ensure that the whole string (for example, fits the defined pattern

  1. After all of that, the check is pretty easy:
screen shot
Fig. 22- Using the RegEx to check the email address

Note Line 84: This completes the jQuery/JavaScript for the assignment

  1. At the bottom of index.html add

    <script src='js/validator.js'></script>

    just above the closing </body> tag
screen shot
Fig. 23- Modify HTML

Remember, any external jQuery file has to be added to the HTML document after the jQuery script file


  1. Save your work and return to the browser. Refresh the page
  1. Test the code under a variety of circumstances:
    • Valid input
    • Both fields empty
    • Just a name (no email address)
    • Just an email address (no name)
    • Invalid email address
      • Missing '@' character
      • Missing ' . ' character
      • Invalid character, i.e., ramsey^

All of the list items above represent use-cases for this project

Remember, if there are errors in your code, the first thing to do is look at the console for error messages. If you do have any errors, they'll probably be typographical

You may be wondering: How could a malicious user hijack this little form? Well, what if the user entered into the field something like


Maybe it wouldn't do anything. But the first part of that bogus email address (before the @ character) is executable code that could potentially create all kinds of mayhem. Without checking it for validity, it could be accepted as a valid email address by the form processor and then maybe end the world as we know it

Finishing up

  1. Once your code is error free, upload the jquery-2 folder to your labs folder on the server using FileZilla
  1. Display the page in your browser and run the above tests again to ensure that no bugs have crept in somehow during transit. Occasionally, for one reason or another, code that works fine in your sandbox environment won't work correctly on the server. They are using (usually) two different operating systems, after all
  1. Copy/paste the URL for the file into a new text document named jquery-2.txt and upload the file to the D2L Dropbox folder, jQuery II

Have a nice day 😊