For today’s tutorial we are going to do something a little more interesting and take several jQuery functions, which have been covered in our previous posts and combine them to create our own form submit process, which will be able to handle all of the forms in our projects.
This is a good exercise to see how various components/snippets can be combined to create a complete function.
The tutorial assumes you have the basic understanding of the HTML and CSS for the form.
The Basic Components
So, in order to create our process we are going to use the following components:
- A general HTML form format
- Our standard CSS rules for styling the form
- Add default text for our input fields, including a function to remove the default text when the form is submitted – see earlier blog post – Add Default Text To Form Fields Using jQuery
- jQuery validation rules, which are applied when a form is submitted
- jQuery code for processing the form and submitting the contents via AJAX
1. HTML Form Format
Obviously everyone has their own preferences when it comes to how you code your form. After experimenting with several different formats I found that using an ordered list to handle the layout, which each form input field and associated label being one list item, has been easiest to use and so far has been robust enough to take most standard form requirements.
For the tutorial we will create a standard contact form with a name field, email, telephone and text area for comments:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
| <form id="form-contact" class="styled" action="/user_functions.php" method="post"> <fieldset> <legend>Contact Form</legend> <ol> <li class="form-row"> <label>Email:</label> <input id="input-email" type="text" class="text-input required email default" name="email" value="" title="Enter Your Email Address" /> </li> <li class="form-row"> <label>Name:</label> <input id="input-name" type="text" class="text-input required default" name="name" value="" title="Enter Your Full Name" /> </li> <li class="form-row"> <label>Phone:</label> <input id="input-phone" type="text" class="text-input" name="phone" value="" /> </li> <li class="form-row"> <label>Comments:</label> <textarea id="input-message" class="text-area" name="message" cols="40" rows="8"></textarea> </li> <li class="button-row text-right"> <input class="btn-submit" type="submit" value="submit" name="submit" /> </li> </ol> </fieldset> </form> |
As usual our jQuery will use css classes and IDs for the selectors. The key ones we need to include are:
- Class “btn-submit” on the form submit button – used to trigger the function.
- Class “required” on any input fields to be validated.
- Class “email” as an additional class on those input fields to be tested against our regular expression for correctly formatted email addressed.
2. The Form CSS
The CSS I use as the basis for this format is as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
| .styled {font-family: Arial, sans-serif;}.styled fieldset {border: 1px solid #ccc; padding: 10px;}.styled fieldset legend {font-size: 16px; font-weight: bold; color: #000; text-transform: capitalize; padding: 5px; background: #fff; display: block; margin-bottom: 0; border: 1px solid #ccc;}.styled fieldset ol, .styled fieldset ol li {list-style: none;}.styled fieldset li.form-row {margin-bottom: 3px; padding: 2px 0; width: 100%; overflow: hidden; position: relative;}.styled label {font-size: 12px; display: block; font-weight: bold; float: left; width: 100px; margin-left: 5px; line-height: 24px;}.styled input.text-input, .styled .text-area {background: #fefefe; border-top: 1px solid #909090; border-right: 1px solid #cecece; border-bottom: 1px solid #e1e1e1; border-left: 1px solid #bbb; padding: 3px; width: 220px; font-size: 12px;}.styled input.text-input.default.active, .styled .text-area.default.active {color: #666; font-style: italic;}.styled fieldset li.button-row {margin-bottom: 0; padding: 2px 5px;}form input.btn-submit {padding: 3px 7px; border: 1px solid #fff; background: #066CAA; font-size: 12px;} |
This is pretty much the minimum styling we need to add to get the labels and input fields aligned and pad/border the form. This can then be applied to your forms by adding the class “styled”. You can build on the above CSS to make your forms a little more exciting!
Any specific rules you may want to add for each form can be done using it’s id. For our contact form #form-contact, we want to set the width to 320px and center on the page.
Validation CSS
In addition to the form layout we also need a few additional CSS rules, which will handle the styling of the validation results:
1
2
3
4
5
6
7
8
9
| .styled span.error {font-size: 11px; position: absolute; top: 0; right: 0; display: block; padding: 2px;}.styled fieldset li.error {color: #D8000C; background: #fff0f0 url(../media/images/checkers.png) repeat; border: 1px solid #f9c7c7; padding: 5px 0;}.styled fieldset li.error label {text-align: left;} |
3. The JQuery Code – Default Text Function
Before we tackle the form submission and validation lets add the jQuery code to handle the default text for the input fields – See earlier post for explanation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| $(".default").each(function(){ var defaultVal = $(this).attr('title'); $(this).focus(function(){ if ($(this).val() == defaultVal){ $(this).removeClass('active').val(''); } }); $(this).blur(function() { if ($(this).val() == ''){ $(this).addClass('active').val(defaultVal); } }) .blur().addClass('active');}); |
We can now add default text to any of our form fields by simply adding the class “default” and using the title attribute to hold the default text. In our contact form example we have decided to add default text to both the email fields and the name field, which are both required.
Since we dont want the default text to be submitted with the form for any empty fields we add a jQuery function, which will automatically check all input fields with class “default” and remove the text if the value is the same as the title attribute:
1
2
3
4
5
6
7
8
| function defaulttextRemove(){ $('.default').each(function(){ var defaultVal = $(this).attr('title'); if ($(this).val() == defaultVal){ $(this).val(''); } });} |
Now for our main function, handling the form submit. There are a few parts to this process:
- Check the form details – i.e. exactly which submit button has been pressed and the action URL for the data, since we are creating a generic function, which can be used by any forms, including multiple instances on one page.
- Run the relevant validation on all required input fields – for our example we have both standard required text field and email validation using regular expressions to check for a correct email format.
- Assuming no errors, we serialize the form data and using AJAX, post the contents to the form URL and return a result.
4. Form Validation And AJAX Form Submit JQuery Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
| // Declare the loading gif as a variable, which will be used latervar $loading = $('<div class="loading"><img src="/media/images/loading.gif" alt="" /></div>');// Form validation and submit when button is clicked$('.btn-submit').click(function(e){ // Declare the function variables - parent form, form URL and the regex for checking the email var $formId = $(this).parents('form'); var formAction = $formId.attr('action'); var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; // In preparation for validating the form - Remove any active default text and previous errors defaulttextRemove(); $('li',$formId).removeClass('error'); $('span.error').remove(); // Start validation by selecting all inputs with the class "required" $('.required',$formId).each(function(){ var inputVal = $(this).val(); var $parentTag = $(this).parent(); if(inputVal == ''){ $parentTag.addClass('error').append('<span class="error">Required field</span>'); } // Run the email validation using the regex for those input items also having class "email" if($(this).hasClass('email') == true){ if(!emailReg.test(inputVal)){ $parentTag.addClass('error').append('<span class="error">Enter a valid email address.</span>'); } } }); // All validation complete - check whether any errors exist - if not submit form if ($('span.error').length == "0") { $formId.append($loading.clone()); $('fieldset',$formId).hide(); $.post(formAction, $formId.serialize(),function(data){ $('.loading').remove(); $formId.append(data).fadeIn(); }); } // Use the following to prevent the form being submitted the standard way e.preventDefault();}); |
When the submit button is clicked all input fields with the class “required” are checked to see if they have a value. If not an error class is applied to the parent list tag (allows us to highlight the complete form row) as well as an error text message inserted after the input field.
If the input field also has the class “email” a further validation check is made using a standard regular expression to see if the text pattern matches that of an email format.
If any of the validation checks return an error then the form submit is stopped. Here we use an extremely easy and effective way of seeing if there are any errors by using $(‘span.error’).length. If length is not “0″ then there are error messages still active.
If all validation is clear we then use the $.post function to submit the form data. At the same time we hide the form contents and replace with a loading gif.
When the data is returned from the AJAX post we then hide the loading gif and replace the form contents with the data itself – usually this would be something like a status message for the user.
The Complete JQuery Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
| jQuery(document).ready(function($) { var $loading = $('<div class="loading"><img src="/media/images/loading.gif" alt="" /></div>'); $(".default").each(function(){ var defaultVal = $(this).attr('title'); $(this).focus(function(){ if ($(this).val() == defaultVal){ $(this).removeClass('active').val(''); } }); $(this).blur(function() { if ($(this).val() == ''){ $(this).addClass('active').val(defaultVal); } }) .blur().addClass('active'); }); $('.btn-submit').click(function(e){ var $formId = $(this).parents('form'); var formAction = $formId.attr('action'); defaulttextRemove(); var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; $('li',$formId).removeClass('error'); $('span.error').remove(); $('.required',$formId).each(function(){ var inputVal = $(this).val(); var $parentTag = $(this).parent(); if(inputVal == ''){ $parentTag.addClass('error').append('<span class="error">Required field</span>'); } if($(this).hasClass('email') == true){ if(!emailReg.test(inputVal)){ $parentTag.addClass('error').append('<span class="error">Enter a valid email address.</span>'); } } }); if ($('span.error').length == "0") { $formId.append($loading.clone()); $('fieldset',$formId).hide(); $.post(formAction, $formId.serialize(),function(data){ $('.loading').remove(); $formId.append(data).fadeIn(); }); } e.preventDefault(); });});function defaulttextRemove(){ $('.default').each(function(){ var defaultVal = $(this).attr('title'); if ($(this).val() == defaultVal){ $(this).val(''); } });} |
No comments:
Post a Comment