Archive for April, 2009

Chuck Season 1 DVD Giveaway!

Wednesday, April 29th, 2009

I am pleased to announce to you all that I am going to give away Chuck Season 1 on DVD to one lucky reader!

If you an unsure of how you can help save chuck or want to know more about the show please visit my earlier post titled Final Push for a Chuck Season 3.

This giveaway is only happening because of the great generosity of @jasononey, so please thank him for his support!

Now how do you go about winning Season 1 on DVD?

All you have to do is:

I will choose the winner by picking a random comment number.

*** Also, I will make sure that the winner is following both of us and has spread this on twitter using the “Spread on Twitter” link.

Good Luck to all, and “Chuck Me” up!

Posted in Uncategorized | 84 Comments »

Building a jQuery Step-by-Step Form

Tuesday, April 28th, 2009

Introduction

A couple weeks ago I was asked to build a long form for accepting camp applications. I know as well as you do how annoying and tedious web forms can get. One thing that I believe enhances a form’s usability is breaking it up into chunks. It is the same concept as breaking up content by using headings as it prevents the visitor from being too overwhelmed and eventually giving up.

I have developed a nice way to give the user a step-by-step form by using jQuery. Let us jump into it below!

Demo

By popular request I have added the demo. View It here!

The HTML

Open a blank HTML file and paste the following in:

< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<title>jQuery Step-by-Step Form | Brenelz Web Solutions</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
</head>

<body>

<h1>Camper Application Form</h1>

<p>Please use this online application form to register for camp.</p>
<form id="camperapplicationForm"method="post" action="">

<div id="first-step">
	<h2>First Step</h2>
	<div>
		<div class="label"><label for="Gender">Gender</label></div>
		<select name="Gender" id="Gender">
			<option value="" selected="selected"></option>
			<option value="Male">Male</option>

			<option value="Female">Female</option>
	    </select>
	</div>

	<div>
		<div class="label"><label for="Grade">Grade in Fall 2009</label></div>
		<select name="Grade" id="Grade">
			<option value="" selected="selected"></option>
			<option value="K">K</option>
			<option value="1">1</option>
			<option value="2">2</option>
			<option value="3">3</option>
			<option value="4">4</option>
			<option value="5">5</option>
			<option value="6">6</option>
			<option value="7">7</option>
			<option value="8">8</option>
			<option value="9">9</option>
			<option value="10">10</option>
			<option value="11">11</option>
			<option value="12">12</option>
	    </select>
	</div>
</div>

<div id="second-step">
	<h2>Second Step</h2>
    <div class="label"><label for="Site">Site</label></div>
    <select name="Site" id="Site">

        <option value="" selected="selected"></option>
        <option value="Cross-View">Cross View (Main Site)</option>
        <option value="Teepee-Village">Teepee Village</option>
        <option value="Mission-Point">Mission Point</option>
    </select>
</div> <!-- end second-step -->

<div id="last-step">
	<h2>Last Step</h2>
	<p>Please select one of the following payment methods.</p>
	<div>
	    <input type="radio" name="payment" id="payment0" value="Credit Card" /><label>Credit Card</label>
	</div>
	<div>
	    <input type="radio" name="payment" id="payment1" value="Cheque" /><label>Cheque</label>
	</div>

	<input type="submit" name="submit" id="submit" value="submit" />
</div> <!-- end last-step -->

</form>
</body>
</html>

Above we have created a short form with 3 steps, which in reality could have many more. The one real important thing to note is that each “step” is wrapped in a <div> with an id. For our example to work, we need to make sure this div is a direct child of the <form> element.

We will hide/show these <div>’s depending on where we are in the signing up process. You may be wondering how we are going to move between the different steps. I have purposely left this out of the HTML, because really we only want those links to show up when JavaScript is enabled. When JavaScript is disabled our whole form will show, and thus do not need the next/previous links. This is termed progressive enhancement in the JavaScript world.

Now onto the jQuery magic!

The jQuery

Setup
// when the dom is ready to be manipulated
$(function(){

    // remember our divs are direct childs of our form
    $('#camperapplicationForm > div')
        .hide();

    // don't forget to show the first step when page is loaded!
    $('#first-step').show();
});

All we are doing here is hiding all the divs by default and enabling the first one as soon as the page loads.

Next/Previous buttons

Creating the next/previous buttons is really the hardest functionality to code. Let’s create a variable to hold our HTML:

		var prevLink = '<a class="prev" href="#">< < Prev</a>';
		var nextLink = '</a><a class="next" href="#">Next >></a>';
		var navHTML = '<div class="prev-next">' +
					  	 prevLink +
						 nextLink +
			             '</div>';

This has not yet put the code into our document… so let’s append the above HTML to every step:

$('#camperapplicationForm > div')
	.hide()
	.append(navHTML);

Now the above will show the next and previous button on every step, but we want to disable the appropriate button when we are on the first or last step. Add the below:

$('#first-step .prev').remove();
$('#last-step .next').remove();

Now we need to code the actual functionality of the buttons:

$('a.next').click(function(){
	$(this).parent().parent().hide().next().show();
});

$('a.prev').click(function(){
	$(this).parent().parent().hide().prev().show();
});

This might seem weird having parent() so often but this is how it breaks down for the previous button:

<form>
     <!-- ($this).parent().parent().prev(); -->
    <div id="second-step">
    </div>

    <!-- ($this).parent().parent() -->
    <div id="last-step">

        <!-- $(this).parent() -->
       <div id="prev-next">

            <!-- $(this) -->
           <a class="prev" href="#">Previous</a>
       </div> <!-- end prev-next -->
    </div> <!-- end last-step -->
</form>

From the above we see we are hiding the current step (Eg. last-step) and showing the previous one (Eg. second-step)

How do we validate each step?

Now that we have our functionality pretty much complete, we turn to how we validate each step separately. Normally we would write some JavaScript to validate the entire form, but in this case that doesn’t work. Remember we only want to validate when the next button is clicked, but not the previous button. Change the “next” function to:


$('a.next').click(function(){
	var whichStep = $(this).parent().parent().attr('id');

	if( whichStep == 'first-step' )
	{
		// validate first-step
	}
	else if( whichStep == 'second-step' )
	{
		// validate second-step
	}
	else if( whichStep == 'last-step' )
	{
		// validate last-step
	}
	$(this).parent().parent().hide().next().show();
});

The Completed Source

< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<title>TUT</title>
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>

    <script type="text/javascript">
		var prevLink = '<a class="prev" href="#">< < Prev</a>';
		var nextLink = '</a><a class="next" href="#">Next >></a>';
		var navHTML = '<div class="prev-next">' +
					  	 prevLink +
						 nextLink +
					  '</div>';
		$(function(){
			// init
			$('#camperapplicationForm > div')
				.hide()
				.append(navHTML);
			$('#first-step .prev').remove();
			$('#last-step .next').remove();

			// show first step
			$('#first-step').show();

			$('a.next').click(function(){
				var whichStep = $(this).parent().parent().attr('id');

				if( whichStep == 'first-step' )
				{
					// validate first-step
				}
				else if( whichStep == 'second-step' )
				{
					// validate second-step
				}
				else if( whichStep == 'last-step' )
				{
					// validate last-step
				}

				$(this).parent().parent().hide().next().show();
			});

			$('a.prev').click(function(){
				$(this).parent().parent().hide().prev().show();
			});
		});
	</script>
</head>

<body>

<h1>Camper Application Form</h1>

<p>Please use this online application form to register for camp.</p>
<form id="camperapplicationForm"method="post" action="">

<div id="first-step">
	<h2>First Step</h2>
	<div>
		<div class="label"><label for="Gender">Gender</label></div>
		<select name="Gender" id="Gender">
			<option value="" selected="selected"></option>
			<option value="Male">Male</option>

			<option value="Female">Female</option>
	    </select>
	</div>

	<div>
		<div class="label"><label for="Grade">Grade in Fall 2009</label></div>
		<select name="Grade" id="Grade">
			<option value="" selected="selected"></option>
			<option value="K">K</option>
			<option value="1">1</option>
			<option value="2">2</option>
			<option value="3">3</option>
			<option value="4">4</option>
			<option value="5">5</option>
			<option value="6">6</option>
			<option value="7">7</option>
			<option value="8">8</option>
			<option value="9">9</option>
			<option value="10">10</option>
			<option value="11">11</option>
			<option value="12">12</option>
	    </select>
	</div>

</div>

<div id="second-step">
	<h2>Second Step</h2>
    <div class="label"><label for="Site">Site</label></div>
    <select name="Site" id="Site">

        <option value="" selected="selected"></option>
        <option value="Cross-View">Cross View (Main Site)</option>
        <option value="Teepee-Village">Teepee Village</option>
        <option value="Mission-Point">Mission Point</option>
    </select>
</div> <!-- end second-step -->

<div id="last-step">
	<h2>Last Step</h2>
	<p>Please select one of the following payment methods.</p>
	<div>
	    <input type="radio" name="payment" id="payment0" value="Credit Card" /><label>Credit Card</label>
	</div>
	<div>
	    <input type="radio" name="payment" id="payment1" value="Cheque" /><label>Cheque</label>
	</div>

	<input type="submit" name="submit" id="submit" value="submit" />
</div> <!-- end last-step -->

</form>
</body>
</html>

Posted in Web Programming | 11 Comments »

Final Push for a Chuck Season 3

Saturday, April 25th, 2009

Before I start, Please digg this post if you like chuck!

Now you may be wondering what a TV show called “Chuck” has to do with web design? Well it doesn’t directly deal with web development, but it does contain numerous geekery. Well actually I do recall that Chuck has XSLT and Programming Perl books in his room.

Anyways, I do not watch a whole lot of TV as I tend to be on the computer most of the day, but this show was one of the few I got hooked on. I really only started watching the show right after this year’s Super bowl. I was amazed at how the show mixed so many genres into one killer show. It had action, romance, and comedy while not making it too forced or unnatural.

What can I do to help Chuck get a Season 3?

There are numerous ways you can spread the Chuck love. Below I have a few listed:

  1. Watch the Chuck season finale live on NBC at 8/7c this Monday and buy a $5 foot long sub from subway
  2. Watch Chuck episodes on Hulu.com and NBC.com
  3. Buy Chuck Season 1 and Pre-order Season 2
  4. Write NBC a letter, send Nerds candy to NBC, and Twitter using hash tags #chuck and #savechuck
  5. Lastly, tell all your friends to do the same!

Why should you watch Chuck?

  • Great guest stars including Scott Bakula and Chevy Chase
  • Sexy Yvonne Strahovski
  • Nerdy Zachary Levi
  • Cold, but kick-butt Adam Baldwin
  • hilarious comedy
  • Great plots
  • Among many other things…

As if you need more incentive but check out the following links:

I have never watched Chuck, What is it about?

It has been said that the finale will be great entertainment without needing to have seen any previous episodes. The finale will be a new launching point for a Season 3 and in a sense is a new pilot. For a quick explanation see the following for Wikipedia.org:

“Chuck is an action-comedy television program from the United States created by Josh Schwartz and Chris Fedak. The series is about an “average computer-whiz-next-door” who receives an encoded e-mail from an old college friend now working in the CIA; the message embeds the only remaining copy of the world’s greatest spy secrets into Chuck’s brain.”

Below are a couple of links that can help you dive further into the Chuck basics:

What sites are great Chuck resources?

Please, please just watch Chuck this Monday at 8/7c on NBC. Just give it a chance this once and I know that you will not be disappointed. Here is to a Season 3 and many more seasons to come!!

I would love to hear your comments on the show below.

Posted in Uncategorized | 20 Comments »

PHP Arrays Unleashed

Monday, April 20th, 2009

Understanding arrays is the first major milestone when learning how to code. An array is not an easy concept to grasp at first since an array has many values, or elements, and can be used in so many ways. Many functions return their results as an array. There is no way around it, if you want to learn how to code, be it in php, javascript or any other language, you will need to understand the array.

What is an array?

A common definition for an array is a list used to organize or group elements. This is, to some degree, an accurate definition. Arrays share many characteristics of a list, but list can only be used to organize items and arrays can do a bit more. A better definition would be that an array is a container where you can organize, group and store items. The big difference being that a container holds the actual items and a list only is a reference of the items. If I give you a list of my tools all you can do is reorganize the list for your own use, but if I give you a box with my tools you can reorganize, borrow, add a new one and then give the box back to me with the modifications you made.

There are two types of arrays: Numerical Arrays (also referred to as Indexed Arrays) and Associative Arrays. However, php does not treat the two types any differently, as far as php is concerned they are both simply arrays.

There are also Multidimensional Arrays, which are arrays, either numerical or associative that have arrays as values (in other words multiple values).

Creating An Array

At first glance an array is very similar to a variable, we identify it with a $ and give it a name.


$variableName

It is when assigning an array’s values that things change. PHP is very flexible and you do not need to declare a variable as an array before using it but we do need to use the correct syntax. The method for defining an array is with the following syntax:

$arrayName = array ("value-1″,"value-2″,"value-3″)

You can also set each array item individually by using the square bracket syntax:

$arrayName[] = "value-1";
$arrayName[] = "value-2";
$arrayName[] = "value-3";

Both methods will result in the same array $arrayName containing the 3 set values. You can even mix the two methods:

$arrayName = array ("value-1″,"value-2″,"value-3″);
$arrayName[] = "value-4";
$arrayName[] = "value-5";

This will result in the $arrayName array having 5 indexed values value-1 to value-5.

note: You could also use the array_push() function to add elements to an array.

note: array values can be strings, integers or arrays.

Array Index

In an array each value gets a unique index, or key assigned to it. In order to return a specific value from the array you need to identify the element by its key. The format of the index key is what defines the type of array. In a numerical array the key is defined by a unique numeric id. If no key value is defined when assigning the array values then php will default to a numerical array. In the previous example we created a numerical array. To get a better understanding let’s look inside this array.

We can view an array’s contents by using the print_r() function. This function is very useful when debugging arrays since it lets you look inside an array’s structure and see it’s element’s key/value relationships. If we run print_r on the array we have just created it will output:

note: wrap the output of print_r with <pre> tags for readable formating

Array
(
    [0] => value-1
    [1] => value-2
    [2] => value-3
    [3] => value-4
    [4] => value-5
)

The index key is displayed in the square bracket [3] and the corresponding value is displayed after the arrow =>. Examine the array output and you will notice two important factors:

  1. the first element is indexed as 0 rather than 1, this is because arrays are 0 based;
  2. the numeric keys are automatically assigned.

Accessing Indexed Array Values

Now that we know the index key that corresponds to the value we want to retrieve from the array we can use the key to isolate the element we want. We know that “value-2″ corresponds to index key 3, and we can echo this value with the following syntax:

echo $arrayName[3]

Associative Arrays

In an associative array the index key is defined by a string rather than an integer. This is a very powerful feature since this will allow us to associate a descriptive key to identify the value as opposed to a non-descriptive number. Associative arrays are set by assigning key => value pairs for each array element. We can use the array() or square bracket format to define an associative array:

$arrayName = array("key1" => "value-1", "key2" => "value-2");
// or use square braket sytax
$arrayName["key3"] = "value-3";
$arrayName["key4"] = "value-4";

Notice the difference when we output the array structure with print_r, the keys are the values that we defined and not numerical:

Array
(
    [key1] => value-1
    [key2] => value-2
    [key3] => value-3
    [key4] => value-4
)

We access the array values in the same way we do with numerical arrays. To return the value of the array element with the key of "key2" we would:

echo $arrayName["key2"];

You can see how this can be very useful if we use descriptive keys:

$dinner["drink"] = "red wine";
$dinner["food"] = "steak";
$dinner["desert"] = "apple pie";

note: you can mix numeric and associative keys in the same array.

The foreach() Loop

We have seen how to return individual values from an array. However, there will be occasions where you will want to go through the structure of an array to interact with the array values. The foreach() loop is the most common method for iterating through an array. It works like a loop that will go through the array and provides a method for you to extract the value or the key => value pair for each array element. The syntax for the foreach function is:

foreach (array as $value) {
    ...
}

Or for returning the key and the value:

foreach (array as $key => $value){
    ...
}

Putting it all together

Let’s see how we can use an array with the foreach loop to generate a link menu. First we create an array to store the information for out menu. The info we need is the link text and the link url. For this we will use an associative array and take advantage of the key value as the link text.

$myMenu["home"] = "home.html";
$myMenu["about"] = "pages/about-us.html";
$myMenu["services"] = "internet/services.html";
$myMenu["contact"] = "form/contact.html";

Now we can use the foreach loop to build the menu output:

foreach($myMenu as $key => $value){
    $output .= "<a href=\"$value\">$key</a><br />\n";
}

echo $output;

This will output our menu as:

<a href="home.html">home</a><br />
<a href="pages/about-us.html">about</a><br />

<a href="internet/services.html">services</a><br />
<a href="form/contact.html">contact</a><br />

Multidimensional Arrays

So far we have worked with simple arrays where there is one key corresponding to a single ‘value’ for each array element. However, what happens if we need more than one key=>value pair per element? We can handle this by using an array as the value for an element so that one key can have multiple values based on a second key layer, or dimension. Like those cool boxes that you open and there is another box inside it.

Expanding on the previous link menu example we can modify the array to include additional fields for our menu.


$myMenu["home"] = array("url" => "home.html", "text" => "Home Page");
$myMenu["about"] = array("url" => "pages/about-us.html", "text" => "About Us");
$myMenu["services"] = array("url" => "internet/services.html", "text" => "Our Services");
$myMenu["contact"] = array("url" => "form/contact.html", "text" => "Contact Us");

To get a clear view of how this array is structured lets look at it with print_r():

Array
(
    [home] => Array
        (
            [url] => home.html
            [text] => Home Page
        )

    [about] => Array
        (
            [url] => pages/about-us.html
            [text] => About Us
        )

    [services] => Array
        (
            [url] => internet/services.html
            [text] => Our Services
        )

    [contact] => Array
        (
            [url] => form/contact.html
            [text] => Contact Us
        )

)

Notice that there are multiple values available for each top level element. We can access the values within the array directly by including the subsequent index key to the array name:

echo "<a href=\"{$myMenu['home']['url']}\" >{$myMenu['home']['text']} </a>";

Notice that we are using the {} around our array, this is the syntax for referencing a complex variable and is referred to as "complex (curly) syntax".

We can iterate through a multidimensional array using the same method as we did with the standard arrays, using the foreach () loop and adding additional loops for each level we want to reach in the array:

foreach($myMenu as $key => $val){
    foreach($val as $k => $v){
        $url = $k;
        $link = $v;
    }
    $output .= "<a href=\"$url\" title=\"$key\" id=\"$key\">$link</a><br />\n";
}

echo $output;

The output will be:

<a href="text" title="home" id="home">Home Page</a><br />

<a href="text" title="about" id="about">About Us</a><br />
<a href="text" title="services" id="services">Our Services</a><br />

<a href="text" title="contact" id="contact">Contact Us</a><br />

As you can see we were successfully able to include additional data to our array.

Array Functions

PHP has a full set of tools that allow you to manipulate and interact with arrays in virtually any way that is needed. Here are some common functions you should know

Sorting Arrays: PHP has many functions for sorting arrays, the most common are the to sort by ‘value’, or sorting by key.

// sort by value
asort($arrayName);

// sort by key
ksort($arrayName);

note: you can also use the sort() function, but this will not retain the key association to the value.

Checking if a variable is an array: Use is_array() to see if a variable is an array.

if(is_array($arrayName){ ... }

Checking if a value is in an arrray: Use in_array() to see if a value is in an array.

if(in_array("value", $arrayName)){ ... }

How many elements in an array: Use count() to return the number of elements in an array.

echo count($arrayName);

How many elements in a multidimensional array: Use the second parameter for count() to enter COUNT_RECURSIVE mode.

echo count($arrayName, 1);

There are many more, be sure to check out the php documentation on array functions for a complete list of the available functions.

Posted in Web Programming | 12 Comments »

CSS Line Break Bug (screencast)

Friday, April 17th, 2009

While working on a client site this week, I came across a very strange bug that I just felt needed to be shared. It appears to happen when an inline element is within another inline element. The simple way to fix this error is to clump your elements together and avoid any line breaks or code indenting. Watch the following video for further information!

Download Source Files

Posted in Uncategorized | 13 Comments »

 
connect with me!