Ajax Updates

Ajax Updates


Autopopulating Select Boxes

Posted: 24 Dec 2009 01:03 PM PST

Allow the user to select a top level category from one select box and to automatically populate the sub-category.
Prerequisites

1. Latest copy of jQuery
2. A basic understanding of JSON (don't let this put you off – it's really very, very easy)
3. A server-side script that can respond to the AJAX request (though I've provided a simple example)

Demo

Our demo will specifically look to build a simple form that allows us to book human resource for a project. The top level category is the resource type, and the sub-category will list the individual's names.

See the demo in action
How it works

Once the top level category select is changed, it sends an AJAX request for the sub-categories. The result of which are converted to select options and the sub-category select's elements are replaced.
Unobtrusive JavaScript

First things first: as with any page that is loaded with JavaScript and AJAX functionality, it should work without JavaScript.

To achieve this for our tutorial here's what we need to ensure:

1. When the page is loaded, the sub-category is loaded (if the top level has a selected item).
2. There is a 'load sub-category' button the user can select to re-load the page. We will hide this button with a

The Code

There are 4 parts to this demo.

1. The page's HTML.
2. The server-side code to produce the dynamic page (i.e. to pre-load the select boxes when the user first visits).
3. The jQuery & JavaScript.
4. The JSON response (which will reuse the server-side code).

HTML

 <form action="/select_demo.php">   <label for="ctlJob">Job Function:</label>   <select name="id" id="ctlJob">     <option value="1">Managers</option>     <option value="2">Team Leaders</option>     <option value="3">Developers</option>   </select>   <noscript>     <input type="submit" name="action" value="Load Individuals" />   </noscript>   <label for="ctlPerson">Individual:</label>   <select name="person_id" id="ctlPerson">     <option value="1">Mark P</option>     <option value="2">Andy Y</option>     <option value="3">Richard B</option>   </select> <input type="submit" name="action" value="Book" /> </form>  

Server-side

This is just a simple example, but it should be obvious that you can expand this to go off to a database and return an object in a JSON data structure:

  < ?php if ($_GET['id'] == 1) {   echo <<<HERE_DOC [ {optionValue: 0, optionDisplay: 'Mark'}, {optionValue:1, optionDisplay: 'Andy'}, {optionValue:2, optionDisplay: 'Richard'}] HERE_DOC; } else if ($_GET['id'] == 2) {   echo <<<HERE_DOC [{optionValue:10, optionDisplay: 'Remy'}, {optionValue:11, optionDisplay: 'Arif'}, {optionValue:12, optionDisplay: 'JC'}] HERE_DOC; } else if ($_GET['id'] == 3) {   echo <<<HERE_DOC [{optionValue:20, optionDisplay: 'Aidan'}, {optionValue:21, optionDisplay:'Russell'}] HERE_DOC; }?> 

Note that this is not accessible. To ensure accessibility, the server side will handle the pre-population of the select boxes as the page is loaded. Here is an example (excluding the headers, footers and JavaScript) of the accessible example.
JSON Response

If I pass the server side id = 2, i.e. /select.php?id=2&ajax=true, the return value is (the ajax=true is an arbitrary flag that I'm using to differentiate between a normal user request and one done via AJAX):

 [ {optionValue:10, optionDisplay: 'Remy'}, {optionValue:11, optionDisplay: 'Arif'}, {optionValue:12, optionDisplay: 'JC'}]  

The enclosing square brackets denotes an array and each element is separated by a comma.

Within the array are three objects. If you're familiar with PHP or Perl, you can basically treat these as hashes. The objects have keys (in this case two keys, one called 'optionValue' and one called 'optionDisplay'), and values. Note that keys don't need to be wrapped in quotes (though in some cases you will need them sometimes).

jQuery & AJAX Request

Our JavaScript is going to attach itself after the page is load, and fire an event each time the job function select box is changed.

The event will send the new value of the select box and reload the contents of the person select box.

Note that I'm be a bit naughty here, in that I'm plugging HTML directly in to the DOM.

Each item in the JSON response is looped round and used to build up the new options for the select box. As the response is an array (as mentioned earlier), we can call the .length method on it.

 <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" charset="utf-8"> $(function(){   $("select#ctlJob").change(function(){     $.getJSON("/select.php",{id: $(this).val(), ajax: 'true'}, function(j){       var options = '';       for (var i = 0; i < j.length; i++) {         options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '';       }       $("select#ctlPerson").html(options);     })   }) }) </script>

Where to take it next

So that's the primer. Next steps: upgrade, integrate, extend and stylise. Below is an example of the category selection when submitting an item for sale on Ebay.


Demo: http://dllurl.com/24
Download: http://dllurl.com/25
Source: http://dllurl.com/23

Related Listings:

  1. Auto Populating Select Boxes Script If you are familiar with using select boxes for categorisation...
  2. AJAX Chained Select Script PHP This script requires PHP. You can also other server...
  3. Incremental Search for Select Boxes – jQuery Plugin Did you ever have to scroll through a select box...

Form Validation with JQuery

Posted: 24 Dec 2009 12:27 PM PST

A single line of jQuery to select the form and apply the validation plugin. And a bit of metadata on each element to specify the validation rules.

Of course that isn’t the only way to specify rules. You also don’t have to rely on those default messages, but they come in handy when starting to setup validation for a form.
[edit]
A few things to look for when playing around with the demo

* After trying to submit an invalid form, the first invalid element is focused, allowing the user to correct the field. If another invalid field, that wasn’t the first one, was focused before submit, that field is focused instead, allowing the user start at the bottom, if he prefers that.
* Before a field is marked as invalid, the validation is lazy: Before submitting the form for the first time, the user can tab through fields without getting annoying messages – he won’t get bugged before he had the chance to actually enter a correct value
* Once a field was marked invalid, it is eagerly validated: As soon as the user entered the necessary value, the error message is removed
* If the user enters something in a non-marked field, and tabs/clicks away from it (blur the field), it is validated – obviously the user had the intention to enter something, but failed to enter the correct value

That behaviour can be irritating when clicking through demos of the validation plugin – it is designed for an unobtrusive user experience, annoying the user as little as possible with unnecessary error messages. So when you try out other demos, try to react like one of your users would, and see if the behaviour is better then. If not, please let me know about any ideas you may have for improvements!

Another common problem occurs with this code:

 $("#myform").validate({  submitHandler: function(form) {    // some other code    // maybe disabling submit button    // then:    $(form).submit();  } });

This results in a too-much-recursion error: $(form).submit() triggers another round of validation, resulting in another call to submitHandler, and voila, recursion. Replace that with form.submit(), which triggers the native submit event instead and not the validation.

So the correct code looks slightly different:

 $("#myform").validate({  submitHandler: function(form) {    form.submit();  } });



Demo: http://dllurl.com/20
Download: http://dllurl.com/21
Source: http://dllurl.com/22

Related Listings:

  1. jVal – jQuery Form Field Validation Plugin jVal is a jQuery form field validation plugin that provides...
  2. jQuery inline form validation Engine When it comes to form validation, it's hard to have...
  3. Form validation with Spry The form validation script with Spry will validate your form...

Scriptaculous Effect Demos

Posted: 24 Dec 2009 12:13 PM PST

Script.aculo.us is a set of JavaScript libraries to enhance the user interface of web sites. It provides an visual effects engine, a drag and drop library (including sortable lists), a couple of controls (Ajax-based autocompletion, in-place editing, sliders).

Quick start
1. Download & install

Using script.aculo.us is easy! First, go to the script.aculo.us downloads page to grab yourself the latest version in a convenient package. Follow the instructions there, then return here.

Next, put prototype.js, scriptaculous.js, builder.js, effects.js, dragdrop.js, slider.js and controls.js in a directory of your website, e.g. /javascripts.

Third, load script.aculo.us in your web page. This is done by linking to the scripts in the head of your document.

 <script src="javascripts/prototype.js" type="text/javascript"></script> <script src="javascripts/scriptaculous.js" type="text/javascript"></script>   

The scriptaculous.js loader script will automatically load in the other libraries.

By default, scriptaculous.js loads all of the other javascript files necessary for effects, drag-and-drop, sliders, and all of the other script.aculo.us features. If you don't need all of the features, you can limit the additional scripts that get loaded by specifying them in a comma-separated list, e.g.:

 <script src="scriptaculous.js?load=effects,dragdrop" type="text/javascript"></script>   

The scripts that can be specified are: builder, effects, dragdrop, controls, and slider

Note that some of the scripts require that others be loaded in order to function properly.
2. Use it!

To call upon the functions, use HTML script tags.
The best way is to define them like this:

 <script type="text/javascript" language="javascript">   // < ![CDATA[   $('element_id').appear();   // ]]> </script>   

This way, you won't have to worry about using characters like < and > in your Java Script code.

You can also use effects inside event handlers:

 <div onclick="$(this).switchOff()">   Click here if you've seen enough. </div>   

If you want to get tricky with it, you can pass extra options to the effect like duration, fps (frames per second), and delay.

  <div onclick="$(this).blindUp({ duration: 16 })">   Click here if you want this to go slooooow. </div>  



Demo: http://ndpsoftware.com/ScriptaculousEffectsDemo.php
Download: http://script.aculo.us/dist/scriptaculous-js-1.8.3.zip
Source: http://wiki.github.com/madrobby/scriptaculous

Related Listings:

  1. Scriptaculous Effect Script Script.aculo.us is a set of JavaScript libraries to enhance the...
  2. jRails – jQuery on Rails jQuery-UI has just gotten a major update to version 1.5...
  3. Change Opacity using Scriptaculous Scriptaculous is a great framework to implement superb animated effects...

Accessible CSS Forms

Posted: 24 Dec 2009 11:49 AM PST

In a recent study of web design patterns, Dr. Melody Ivory found that accessibility is the most underutilized aspect of good web page design (Ivory 2005). In fact websites have become more complex and less accessible over time (Hackett 2003). Less than 20% of the Fortune 100 have websites that are fully accessible (Loiacono 2004). Accessible forms are one way to combat this disturbing trend. With CSS layout, you can create two-column forms without the use of tables to save space and time. This article shows how to create a simple two-column contact form using CSS to style structural elements that is both fast and accessible.

A survey of CSS-based forms revealed many variations on a theme (see Vandersluis 2004). Most use block-level floats and margins to position form elements on the page. However, in my testing I found IE5.x Mac to have rendering problems with many of these forms. After numerous iterations, I arrived at a solution that worked for IE5.x Mac as well as Safari 1.07 Mac, Firefox 1.07 Win/Mac, IE 6 Win, Camino, and Opera. Our goal here is to create a simple accessible contact form without the use of tables (see Figure 1).

Table-Based Contact Form

First let’s look at the old way of laying out a form. Tables use columns and rows to align labels and input fields (see Figure 2).

  <form action="http://www.example.com/submit.cgi" method="post" class="ft"> <table> 	<colgroup><col align="right"></col><col align="left"></col></colgroup> 	<tr><th colspan="2"><h3>Personal Information</h3></th></tr> 	<tr><th>First name:</th> 		<td><input type="text" name="firstname" value="" title="first name"/></td><td></td></tr> 	<tr><th>Last name:</th> 		<td><input type="text" name="lastname" title="last name"/></td></tr> 	<tr><th>Email:</th> 		<td><input type="text" name="email" title="email"/></td><td></td></tr>  	<tr><th colspan="2"><h3>Comments</h3></th></tr> 	<tr><th>Your comments:</th> 		<td><textarea name="comments" rows="3" cols="20" title="comments"></textarea></td></tr> 	<tr><td></td><td><input type="submit" value="Send"/> <input type="reset" id="reset"/></td></tr> </table> </form> 

Note how much of the XHTML code is used for layout. Note also that this is an minimalist example with little or no accessibility features. The resulting table looks something like this rendered in a browser.

Unfortunately, laying out a form with tables can make it difficult to access for folks with disabilities. Table-based layout also lowers your content to markup ratio, which reduces potential SEO rankings and speed. Fortunately there is a better way, CSS layout.
Building a CSS-based Form

The key to any CSS conversion project is to strip down your XHTML to bare structural elements, and then use CSS to contextually target as much style and layout as possible using few embedded classes or IDs. Forms are no different. What the table-based form above is missing are semantic elements the W3C provides in the (X)HTML specifications, namely FIELDSET and LABEL. Although they can be funkily interpreted for background colors, FIELDSET and LABEL give logical order to FORMs. FIELDSET groups like-minded form input fields and LABEL FOR links field labels with input fields through the ID attribute to make them more accessible and eminently stylable. Let’s take the above table-based form code and strip it down to the bare essentials.

 <form action="http://www.example.com/submit.cgi" method="post" name="f"> 	<fieldset> 		<legend>Personal Information</legend>> 			<label for="firstname" accesskey="f">First name: </label> 				<input type="text" id="firstname" name="firstname" value="" tabindex="1"/> 			<label for="lastname" accesskey="l">Last name: </label> 				<input type="text" id="lastname" name="lastname" tabindex="2"/> 			<label for="email" accesskey="e">Email: </label> 				<input type="text" id="email" name="email" tabindex="3"/> 	</fieldset> 	<fieldset> 		<legend>Comments</legend> 			<label for="comments" accesskey="c">Your comments: </label> 				<textarea id="comments" rows="3" cols="20" name="comments"></textarea> 				<input type="submit" value="Submit" tabindex="4"/> <input type="Reset" tabindex="5"/> 	</fieldset> </form>  

This barebones contact form contains the same fields, but they are now surrounded by semantic markup, not layout. The first FIELDSET groups the personal data together, while the second groups the comment field into one group. This style-free form looks like this (see Figure 2).

   
   



Demo: http://www.websiteoptimization.com/speed/tweak/forms/
Source: http://www.websiteoptimization.com/speed/tweak/forms/

Related Listings:

  1. Form Layout Stylish and Accessible Yes, HTML forms are the worst things known to...
  2. Accessible, stylish form layout Yes, HTML forms are the worst things known to web...
  3. Form With Style – Ajax Script Forms are not very friendly when it comes to CSS...

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.