21 Tips to Increase Blog Traffic

১১/২৫/২০১১ ০১:০৪:০০ AM | , , | 0 comments »

A considerable portion of my consulting time has recently revolved around the optimization of corporate blogs (or the addition of blogs to revamped sites). As usual, I find a pattern emerging in the strategies that need attention and the pitfalls that must be avoided. So, rather than charging $400 an hour to give advice on the subject, I thought it would be valuable to share many of the most common pieces of advice here on the blog (business part of Rand fights with open source Rand, but loses, as usual).
  1. Choose the Right Blog Software (or Custom Build)
    The right blog CMS makes a big difference. If you want to set yourself apart, I recommend creating a custom blog solution - one that can be completely customized to your users. In most cases, WordPress, Blogger, MovableType or Typepad will suffice, but building from scratch allows you to be very creative with functionality and formatting. The best CMS is something that's easy for the writer(s) to use and brings together the features that allow the blog to flourish. Think about how you want comments, archiving, sub-pages, categorization, multiple feeds and user accounts to operate in order to narrow down your choices. OpenSourceCMS is a very good tool to help you select a software if you go that route.
    -
  2. Host Your Blog Directly on Your Domain
    Hosting your blog on a different domain from your primary site is one of the worst mistakes you can make. A blog on your domain can attract links, attention, publicity, trust and search rankings - by keeping the blog on a separate domain, you shoot yourself in the foot. From worst to best, your options are - Hosted (on a solution like Blogspot or Wordpress), on a unique domain (at least you can 301 it in the future), on a subdomain (these can be treated as unique from the primary domain by the engines) and as a sub-section of the primary domain (in a subfolder or page - this is the best solution).
    -
  3. Write Title Tags with Two Audiences in Mind
    First and foremost, you're writing a title tag for the people who will visit your site or have a subscription to your feed. Title tags that are short, snappy, on-topic and catchy are imperative. You also want to think about search engines when you title your posts, since the engines can help to drive traffic to your blog. A great way to do this is to write the post and the title first, then run a few searches at Overture, WordTracker & KeywordDiscovery to see if there is a phrasing or ordering that can better help you to target "searched for" terms.
    -
  4. Participate at Related Forums & BlogsWhatever industry or niche you're in, there are bloggers, forums and an online community that's already active. Depending on the specificity of your focus, you may need to think one or two levels broader than your own content to find a large community, but with the size of the participatory web today, even the highly specialized content areas receive attention. A great way to find out who these people are is to use Technorati to conduct searches, then sort by number of links (authority). Del.icio.us tags are also very useful in this process, as are straight searches at the engines (Ask.com's blog search in particular is of very good quality).
    -
  5. Tag Your Content
    Technorati is the first place that you should be tagging posts. I actually recommend having the tags right on your page, pointing to the Technorati searches that you're targeting. There are other good places to ping - del.icio.us and Flickr being the two most obvious (the only other one is Blogmarks, which is much smaller). Tagging content can also be valuable to help give you a "bump" towards getting traffic from big sites like Reddit, Digg & StumbleUpon (which requires that you download the toolbar, but trust me - it's worth it). You DO NOT want to submit every post to these sites, but that one out of twenty (see tactic #18) is worth your while.
    -
  6. Launch Without Comments (and Add Them Later)There's something sad about a blog with 0 comments on every post. It feels dead, empty and unpopular. Luckily, there's an easy solution - don't offer the ability to post comments on the blog and no one will know that you only get 20 uniques a day. Once you're upwards of 100 RSS subscribers and/or 750 unique visitors per day, you can open up the comments and see light activity. Comments are often how tech-savvy new visitors judge the popularity of a site (and thus, its worth), so play to your strengths and keep your obscurity private.
    -
  7. Don't Jump on the Bandwagon
    Some memes are worthy of being talked about by every blogger in the space, but most aren't. Just because there's huge news in your industry or niche DOES NOT mean you need to be covering it, or even mentioning it (though it can be valuable to link to it as an aside, just to integrate a shared experience into your unique content). Many of the best blogs online DO talk about the big trends - this is because they're already popular, established and are counted on to be a source of news for the community. If you're launching a new blog, you need to show people in your space that you can offer something unique, different and valuable - not just the same story from your point of view. This is less important in spaces where there are very few bloggers and little online coverage and much more in spaces that are overwhelmed with blogs (like search, or anything else tech-related).
    -
  8. Link Intelligently
    When you link out in your blog posts, use convention where applicable and creativity when warranted, but be aware of how the links you serve are part of the content you provide. Not every issue you discuss or site you mention needs a link, but there's a fine line between overlinking and underlinking. The best advice I can give is to think of the post from the standpoint of a relatively uninformed reader. If you mention Wikipedia, everyone is familiar and no link is required. If you mention a specific page at Wikipedia, a link is necessary and important. Also, be aware that quoting other bloggers or online sources (or even discussing their ideas) without linking to them is considered bad etiquette and can earn you scorn that could cost you links from those sources in the future. It's almost always better to be over-generous with links than under-generous. And link condoms? Only use them when you're linking to something you find truly distasteful or have serious apprehension about.
    -
  9. Invite Guest Bloggers
    Asking a well known personality in your niche to contribute a short blog on their subject of expertise is a great way to grow the value and reach of your blog. You not only flatter the person by acknowledging their celebrity, you nearly guarantee yourself a link or at least an association with a brand that can earn you readers. Just be sure that you really are getting a quality post from someone that's as close to universally popular and admired as possible (unless you want to start playing the drama linkbait game, which I personally abhor). If you're already somewhat popular, it can often be valuable to look outside your space and bring in guest authors who have a very unique angle or subject matter to help spice up your focus. One note about guest bloggers - make sure they agree to have their work edited by you before it's posted. A disagreement on this subject after the fact can have negative ramifications.
    -
  10. Eschew Advertising (Until You're Popular)
    I hate AdSense on blogs. Usually, I ignore it, but I also cast a sharp eye towards the quality of the posts and professionalism of the content when I see AdSense. That's not to say that contextual advertising can't work well in some blogs, but it needs to be well integrated into the design and layout to help defer criticism. Don't get me wrong - it's unfair to judge a blog by its cover (or, in this case, its ads), but spend a lot of time surfing blogs and you'll have the same impression - low quality blogs run AdSense and many high quality ones don't. I always recommend that whether personal or professional, you wait until your blog has achieved a level of success before you start advertising. Ads, whether they're sponsorships, banners, contextual or other, tend to have a direct, negative impact on the number of readers who subscribe, add to favorites and link - you definitely don't want that limitation while you're still trying to get established.
    -
  11. Go Beyond Text in Your Posts
    Blogs that contain nothing but line after line of text are more difficult to read and less consistently interesting than those that offer images, interactive elements, the occasional multimedia content and some clever charts & graphs. Even if you're having a tough time with non-text content, think about how you can format the text using blockquotes, indentation, bullet points, etc. to create a more visually appealing and digestible block of content.
    -
  12. Cover Topics that Need Attention
    In every niche, there are certain topics and questions that are frequently asked or pondered, but rarely have definitive answers. While this recommendation applies to nearly every content-based site, it's particularly easy to leverage with a blog. If everyone in the online Nascar forums is wondering about the components and cost of an average Nascar vehicle - give it to them. If the online stock trading industry is rife with questions about the best performing stocks after a terrorist threat, your path is clear. Spend the time and effort to research, document and deliver and you're virtually guaranteed link-worthy content that will attract new visitors and subscribers.
    -
  13. Pay Attention to Your Analytics
    Visitor tracking software can tell you which posts your audience likes best, which ones don't get viewed and how the search engines are delivering traffic. Use these clues to react and improve your strategies. Feedburner is great for RSS and I'm a personal fan of Indextools. Consider adding action tracking to your blog, so you can see what sources of traffic are bringing the best quality visitors (in terms of time spent on the site, # of page views, etc). I particularly like having the "register" link tagged for analytics so I can see what percentage of visitors from each source is interested enough to want to leave a comment or create an account.
    -
  14. Use a Human Voice
    Charisma is a valuable quality, both online and off. Through a blog, it's most often judged by the voice you present to your users. People like empathy, compassion, authority and honesty. Keep these in the forefront of your mind when writing and you'll be in a good position to succeed. It's also critical that you maintain a level of humility in your blogging and stick to your roots. When users start to feel that a blog is taking itself too seriously or losing the characteristics that made it unique, they start to seek new places for content. We've certainly made mistakes (even recently) that have cost us some fans - be cautious to control not only what you say, but how you say it. Lastly - if there's a hot button issue that has you posting emotionally, temper it by letting the post sit in draft mode for an hour or two, re-reading it and considering any revisions. With the advent of feeds, once you publish, there's no going back.
    -
  15. Archive Effectively
    The best archives are carefully organized into subjects and date ranges. For search traffic (particularly long tail terms), it can be best to offer the full content of every post in a category on the archive pages, but from a usability standpoint, just linking to each post is far better (possibly with a very short snippet). Balance these two issues and make the decision based on your goals. A last note on archiving - pagination in blogging can be harmful to search traffic, rather than beneficial (as you provide constantly changing, duplicate content pages). Pagination is great for users who scroll to the bottom and want to see more, though, so consider putting a "noindex" in the meta tag or in the robots.txt file to keep spiders where they belong - in the well-organized archive system.
    -
  16. Implement Smart URLs
    The best URL structure for blogs is, in my opinion, as short as possible while still containing enough information to make an educated guess about the content you'll find on the page. I don't like the 10 hyphen, lengthy blog titles that are the byproduct of many CMS plugins, but they are certainly better than any dynamic parameters in the URL. Yes - I know I'm not walking the talk here, and hopefully it's something we can fix in the near future. To those who say that one dynamic parameter in the URL doesn't hurt, I'd take issue - just re-writing a ?ID=450 to /450 has improved search traffic considerably on several blogs we've worked with.
    -
  17. Reveal as Much as Possible
    The blogosphere is in love with the idea of an open source world on the web. Sharing vast stores of what might ordinarily be considered private information is the rule, rather than the exception. If you can offer content that's usually private - trade secrets, pricing, contract issues, and even the occasional harmless rumor, your blog can benefit. Make a decision about what's off-limits and how far you can go and then push right up to that limit in order to see the best possible effects. Your community will reward you with links and traffic.
    -
  18. Only One Post in Twenty Can Be Linkbait
    Not every post is worthy of making it to the top of Digg, Del.icio.us/popular or even a mention at some other blogs in your space. Trying to over-market every post you write will result in pushback and ultimately lead to negative opinions about your efforts. The less popular your blog is, the harder it will be to build excitement around a post, but the process of linkbait has always been trial and error - build, test, refine and re-build. Keep creating great ideas and bolstering them with lots of solid, everyday content and you'll eventually be big enough to where one out of every 20-40 posts really does become linkbait.
    -
  19. Make Effective Use of High Traffic DaysIf you do have linkbait, whether by design or by accident, make sure to capitalize. When you hit the front page of Digg, Reddit, Boing Boing, or, on a smaller scale, attract a couple hundred visitors from a bigger blog or site in your space, you need to put your best foot forward. Make sure to follow up on a high traffic time period with 2-3 high quality posts that show off your skills as a writer, your depth of understanding and let visitors know that this is content they should be sticking around to see more of. Nothing kills the potential linkbait "bump" faster than a blog whose content doesn't update for 48 hours after they've received a huge influx of visitors.
    -
  20. Create Expectations and Fulfill Them
    When you're writing for your audience, your content focus, post timing and areas of interest will all become associated with your personal style. If you vary widely from that style, you risk alienating folks who've come to know you and rely on you for specific data. Thus, if you build a blog around the idea of being an analytical expert in your field, don't ignore the latest release of industry figures only to chat about an emotional issue - deliver what your readers expect of you and crunch the numbers. This applies equally well to post frequency - if your blog regularly churns out 2 posts a day, having two weeks with only 4 posts is going to have an adverse impact on traffic. That's not to say you can't take a vacation, but you need to schedule it wisely and be prepared to lose RSS subscribers and regulars. It's not fair, but it's the truth. We lose visitors every time I attend an SES conference and drop to one post every two days (note - guest bloggers and time-release posts can help here, too).
    -
  21. Build a Brand
    Possibly one of the most important aspects of all in blogging is brand-building. As Zefrank noted, to be a great brand, you need to be a brand that people want to associate themselves with and a brand that people feel they derive value from being a member. Exclusivity, insider jokes, emails with regulars, the occasional cat post and references to your previous experiences can be off putting for new readers, but they're solid gold for keeping your loyal base feeling good about their brand experience with you. Be careful to stick to your brand - once you have a definition that people like and are comfortable with, it's very hard to break that mold without severe repercussions. If you're building a new blog, or building a low-traffic one, I highly recommend writing down the goals of your brand and the attributes of its identity to help remind you as you write.
Best of luck to all you bloggers out there. It's an increasingly crowded field to play in, but these strategies should help to give you an edge over the competition. As always, if you've got additions or disagreements, I'd love to hear them.
p.s. Note to self - starting long blog entries at 11:30pm is not conducive to a good night's sleep. At least Angela got kicked off Project Runway tonight.

Pre-Activated Internet Download Manager 6.7 Build 15 Full Version

Release Date : 14 November 2011

undefined


Just Install Setup.
Its a Pre-Activated Full Version.
No need to Use any Crack Or Serial. Enjoy—– 
Here is the link
Click Here

PHP Require (PHP Tutorial part 10)

১১/২২/২০১১ ০৪:৪১:০০ AM | , | 0 comments »

Just like the previous lesson, the require command is used to include a file into your PHP code. However there is one huge difference between the two commands, though it might not seem that big of a deal.

Require vs Include

When you include a file with the include command and PHP cannot find it you will see an error message like the following:

PHP Code:

<?php
include("noFileExistsHere.php");
echo "Hello World!";
?>

Display:

Warning: main(noFileExistsHere.php): failed to open stream: No such file or directory in /home/websiteName/FolderName/tizagScript.php on line 2 Warning: main(): Failed opening 'noFileExistsHere.php' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/websiteName/FolderName/tizagScript.php on line 2

Hello World!
Notice that our echo statement is still executed, this is because a Warning does not prevent our PHP script from running. On the other hand, if we did the same example but used the require statement we would get something like the following example.

PHP Code:

<?php
require("noFileExistsHere.php");
echo "Hello World!";
?>

Display:

Warning: main(noFileExistsHere.php): failed to open stream: No such file or directory in /home/websiteName/FolderName/tizagScript.php on line 2
Fatal error: main(): Failed opening required 'noFileExistsHere.php' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/websiteName/FolderName/tizagScript.php on line 2
The echo statement was not executed because our script execution died after the require command returned a fatal error! We recommend that you use require instead of include because your scripts should not be executing if necessary files are missing or misnamed.

PHP Include (PHP Tutorial part 9)

১১/২২/২০১১ ০৪:৩৯:০০ AM | , | 0 comments »

Without understanding much about the details of PHP, you can save yourself a great deal of time with the use of the PHP include command. include takes a file name and simply inserts that file's contents into the script that issued the include command.

Why is this a cool thing? Well, first of all, this means that you can type up a common header or menu file that you want all your web pages to include. When you add a new page to your site, instead of having to update the links on several web pages, you can simply change the Menu file.

An Include Example

Say we wanted to create a common menu file that all our pages will use. A common practice for naming files that are to be included is to use the ".php" extension. Since we want to create a common menu let's save it as "menu.php".

menu.php Code:

<html>
<body>
<a href="http://www.example.com/index.php">Home</a> - 
<a href="http://www.example.com/about.php">About Us</a> - 
<a href="http://www.example.com/links.php">Links</a> - 
<a href="http://www.example.com/contact.php">Contact Us</a> <br />
Save the above file as "menu.php". Now create a new file, "index.php" in the same directory as "menu.php". Here we will take advantage of the include command to add our common menu.

index.php Code:

<?php include("menu.php"); ?>
<p>This is my home page that uses a common menu to save me time when I add
new pages to my website!</p>
</body>
</html>

Display:

Home - About Us - Links - Contact UsThis is my home page that uses a common menu to save me time when I add new pages to my website!
And we would do the same thing for "about.php", "links.php", and "contact.php". Just think how terrible it would be if you had 15 or more pages with a common menu and you decided to add another web page to that site. You would have to go in and manually edit every single file to add this new page, but with include files you simply have to change "menu.php" and all your problems are solved. Avoid such troublesome occasions with a simple include file.

What do Visitors See?

If we were to use the include command to insert a menu on each of our web pages, what would the visitor see if they viewed the source of "index.php"? Well, because the include command is pretty much the same as copying and pasting, the visitors would see:

View Source of index.php to a Visitor:

<html>
<body>
<a href="index.php">Home</a> - 
<a href="about.php">About Us</a> - 
<a href="links.php">Links</a> - 
<a href="contact.php">Contact Us</a> <br />
<p>This is my home page that uses a common menu to save me time when I add
new pages to my website!</p>
</body>
</html>
The visitor would actually see all the HTML code as one long line of HTML code, because we have not inserted any new line characters. We did some formatting above to make it easier to read. We will be discussing new line characters later.

Include Recap

The include command simply takes all the text that exists in the specified file and copies it into the file that uses the include command. Include is quite useful when you want to include the same PHP, HTML, or text segment on multiple pages of a website. The include command is used widely by PHP web developers. Like PHP Echo, include is not a function, but a language construct.
The next lesson will talk about a slight variation of the include command: require. It is often best to use the require command instead of the include command in your PHP Code. Read the next lesson to find out why!

Using Comments in PHP (PHP Tutorial part 8)

১১/২২/২০১১ ০৪:৩৬:০০ AM | , | 0 comments »

Comments in PHP are similar to comments that are used in HTML. The PHP comment syntax always begins with a special character sequence and all text that appears between the start of the comment and the end will be ignored.

In HTML a comment's main purpose is to serve as a note to you, the web developer or to others who may view your website's source code. However, PHP's comments are different in that they will not be displayed to your visitors. The only way to view PHP comments is to open the PHP file for editing. This makes PHP comments only useful to PHP programmers.
In case you forgot what an HTML comment looked like, see our example below.

HTML Code:

<!-- This is an HTML Comment -->

PHP Comment Syntax: Single Line Comment

While there is only one type of comment in HTML, PHP has two types. The first type we will discuss is the single line comment. The single line comment tells the interpreter to ignore everything that occurs on that line to the right of the comment. To do a single line comment type "//" or "#" and all text to the right will be ignored by PHP interpreter.

PHP Code:

<?php
echo "Hello World!"; // This will print out Hello World!
echo "<br />Psst...You can't see my PHP comments!"; // echo "nothing";
// echo "My name is Humperdinkle!";
# echo "I don't do anything either";
?>

Display:

Hello World!
Psst...You can't see my PHP comments!
Notice that a couple of our echo statements were not evaluated because we commented them out with the single line comment. This type of line commenting is often used for quick notes about complex and confusing code or to temporarily remove a line of PHP code.

PHP Comment Syntax: Multiple Line Comment

Similiar to the HTML comment, the multi-line PHP comment can be used to comment out large blocks of code or writing multiple line comments. The multiple line PHP comment begins with " /* " and ends with " */ ".

PHP Code:

<?php
/* This Echo statement will print out my message to the
the place in which I reside on.  In other words, the World. */
echo "Hello World!"; 
/* echo "My name is Humperdinkle!";
echo "No way! My name is Uber PHP Programmer!";
*/
?>

Display:

Hello World!

Good Commenting Practices

One of the best commenting practices that I can recommend to new PHP programmers is....USE THEM!! So many people write complex PHP code and are either too lazy to write good comments or believe the commenting is not needed. However, do you really believe that you will remember exactly what you were thinking when looking at this code a year or more down the road?
Let the comments permeate your code and you will be a happier PHPer in the future. Use single line comments for quick notes about a tricky part in your code and use multiple line comments when you need to describe something in greater depth than a simple note.

PHP Operators (PHP Tutorial part 7)

১১/২২/২০১১ ০৪:৩৫:০০ AM | , | 0 comments »

In all programming languages, operators are used to manipulate or perform operations on variables and values. You have already seen the string concatenation operator "." in the Echo Lesson and the assignment operator "=" in pretty much every PHP example so far.

There are many operators used in PHP, so we have separated them into the following categories to make it easier to learn them all.
  • Assignment Operators
  • Arithmetic Operators
  • Comparison Operators
  • String Operators
  • Combination Arithmetic & Assignment Operators

Assignment Operators

Assignment operators are used to set a variable equal to a value or set a variable to another variable's value. Such an assignment of value is done with the "=", or equal character. Example:
  • $my_var = 4;
  • $another_var = $my_var;
Now both $my_var and $another_var contain the value 4. Assignments can also be used in conjunction with arithmetic operators.

Arithmetic Operators

OperatorEnglishExample
+Addition2 + 4
-Subtraction6 - 2
*Multiplication5 * 3
/Division15 / 3
%Modulus43 % 10

PHP Code:

$addition = 2 + 4; 
$subtraction = 6 - 2; 
$multiplication = 5 * 3; 
$division = 15 / 3; 
$modulus = 5 % 2; 
echo "Perform addition: 2 + 4 = ".$addition."<br />"; 
echo "Perform subtraction: 6 - 2 = ".$subtraction."<br />"; 
echo "Perform multiplication:  5 * 3 = ".$multiplication."<br />"; 
echo "Perform division: 15 / 3 = ".$division."<br />"; 
echo "Perform modulus: 5 % 2 = " . $modulus 
 . ". Modulus is the remainder after the division operation has been performed.  
 In this case it was 5 / 2, which has a remainder of 1.";

Display:

Perform addition: 2 + 4 = 6
Perform subtraction: 6 - 2 = 4
Perform multiplication: 5 * 3 = 15
Perform division: 15 / 3 = 5
Perform modulus: 5 % 2 = 1. Modulus is the remainder after the division operation has been performed. In this case it was 5 / 2, which has a remainder of 1.

Comparison Operators

Comparisons are used to check the relationship between variables and/or values. If you would like to see a simple example of a comparison operator in action, check out our If Statement Lesson. Comparison operators are used inside conditional statements and evaluate to either true or false. Here are the most important comparison operators of PHP.
Assume: $x = 4 and $y = 5;
OperatorEnglishExampleResult
==Equal To$x == $yfalse
!=Not Equal To$x != $ytrue
<Less Than$x < $ytrue
>Greater Than$x > $yfalse
<=Less Than or Equal To$x <= $ytrue
>=Greater Than or Equal To$x >= $yfalse

String Operators

As we have already seen in the Echo Lesson, the period "." is used to add two strings together, or more technically, the period is the concatenation operator for strings.

PHP Code:

$a_string = "Hello";
$another_string = " Billy";
$new_string = $a_string . $another_string;
echo $new_string . "!";

Display:

Hello Billy!

Combination Arithmetic & Assignment Operators

In programming it is a very common task to have to increment a variable by some fixed amount. The most common example of this is a counter. Say you want to increment a counter by 1, you would have:
  • $counter = $counter + 1;
However, there is a shorthand for doing this.
  • $counter += 1;
This combination assignment/arithmetic operator would accomplish the same task. The downside to this combination operator is that it reduces code readability to those programmers who are not used to such an operator. Here are some examples of other common shorthand operators. In general, "+=" and "-=" are the most widely used combination operators.
OperatorEnglishExampleEquivalent Operation
+=Plus Equals$x += 2;$x = $x + 2;
-=Minus Equals$x -= 4;$x = $x - 4;
*=Multiply Equals$x *= 3;$x = $x * 3;
/=Divide Equals$x /= 2;$x = $x / 2;
%=Modulo Equals$x %= 5;$x = $x % 5;
.=Concatenate Equals$my_str.="hello";$my_str = $my_str . "hello";

Pre/Post-Increment & Pre/Post-Decrement

This may seem a bit absurd, but there is even a shorter shorthand for the common task of adding 1 or subtracting 1 from a variable. To add one to a variable or "increment" use the "++" operator:
  • $x++; Which is equivalent to $x += 1; or $x = $x + 1;
To subtract 1 from a variable, or "decrement" use the "--" operator:
  • $x--; Which is equivalent to $x -= 1; or $x = $x - 1;
In addition to this "shorterhand" technique, you can specify whether you want to increment before the line of code is being executed or after the line has executed. Our PHP code below will display the difference.

PHP Code:

$x = 4;
echo "The value of x with post-plusplus = " . $x++;
echo "<br /> The value of x after the post-plusplus is " . $x;
$x = 4;
echo "<br />The value of x with with pre-plusplus = " . ++$x;
echo "<br /> The value of x after the pre-plusplus is " . $x;

Display:

The value of x with post-plusplus = 4
The value of x after the post-plusplus is = 5
The value of x with with pre-plusplus = 5
The value of x after the pre-plusplus is = 5
As you can see the value of $x++ is not reflected in the echoed text because the variable is not incremented until after the line of code is executed. However, with the pre-increment "++$x" the variable does reflect the addition immediately.

PHP Strings (PHP Tutorial part 6)

১১/২২/২০১১ ০৪:৩৩:০০ AM | , | 0 comments »

In the last lesson, PHP Echo, we used strings a bit, but didn't talk about them in depth. Throughout your PHP career you will be using strings a great deal, so it is important to have a basic understanding of PHP strings.

PHP - String Creation

Before you can use a string you have to create it! A string can be used directly in a function or it can be stored in a variable. Below we create the exact same string twice: first storing it into a variable and in the second case we send the string directly to echo.

PHP Code:

$my_string = "Tizag - Unlock your potential!";
echo "Tizag - Unlock your potential!";
echo $my_string;
In the above example the first string will be stored into the variable $my_string, while the second string will be used in the echo and not be stored. Remember to save your strings into variables if you plan on using them more than once! Below is the output from our example code. They look identical just as we thought.

Display:

Tizag - Unlock your potential! Tizag - Unlock your potential!

PHP - String Creation Single Quotes

Thus far we have created strings using double-quotes, but it is just as correct to create a string using single-quotes, otherwise known as apostrophes.

PHP Code:

$my_string = 'Tizag - Unlock your potential!';
echo 'Tizag - Unlock your potential!';
echo $my_string;
If you want to use a single-quote within the string you have to escape the single-quote with a backslash \ . Like this: \' !

PHP Code:

echo 'Tizag - It\'s Neat!';

PHP - String Creation Double-Quotes

We have used double-quotes and will continue to use them as the primary method for forming strings. Double-quotes allow for many special escaped characters to be used that you cannot do with a single-quote string. Once again, a backslash is used to escape a character.

PHP Code:

$newline = "A newline is \n";
$return = "A carriage return is \r";
$tab = "A tab is \t";
$dollar = "A dollar sign is \$";
$doublequote = "A double-quote is \"";
Note: If you try to escape a character that doesn't need to be, such as an apostrophe, then the backslash will show up when you output the string.
These escaped characters are not very useful for outputting to a web page because HTML ignore extra white space. A tab, newline, and carriage return are all examples of extra (ignorable) white space. However, when writing to a file that may be read by human eyes these escaped characters are a valuable tool!

PHP - String Creation Heredoc

The two methods above are the traditional way to create strings in most programming languages. PHP introduces a more robust string creation tool called heredoc that lets the programmer create multi-line strings without using quotations. However, creating a string using heredoc is more difficult and can lead to problems if you do not properly code your string! Here's how to do it:

PHP Code:

$my_string = <<<TEST
Tizag.com
Webmaster Tutorials
Unlock your potential!
TEST;

echo $my_string;
There are a few very important things to remember when using heredoc.
  • Use <<< and some identifier that you choose to begin the heredoc. In this example we chose TEST as our identifier.
  • Repeat the identifier followed by a semicolon to end the heredoc string creation. In this example that was TEST;
  • The closing sequence TEST; must occur on a line by itself and cannot be indented!
Another thing to note is that when you output this multi-line string to a web page, it will not span multiple lines because we did not have any <br /> tags contained inside our string! Here is the output made from the code above.

Display:

Tizag.com Webmaster Tutorials Unlock your potential!
Once again, take great care in following the heredoc creation guidelines to avoid any headaches.

PHP Echo (PHP Tutorial part 5)

১১/২২/২০১১ ০৪:৩২:০০ AM | , | 0 comments »

As you saw in the previous lesson, the PHP command echo is a means of outputting text to the web browser. Throughout your PHP career you will be using the echo command more than any other. So let's give it a solid perusal!

Outputting a String

To output a string, like we have done in previous lessons, use PHP echo. You can place either a string variable or you can use quotes, like we do below, to create a string that the echo function will output.

PHP Code:

<?php
$myString = "Hello!";
echo $myString;
echo "<h5>I love using PHP!</h5>";
?>

Display:

Hello!
I love using PHP!
In the above example we output "Hello!" without a hitch. The text we are outputting is being sent to the user in the form of a web page, so it is important that we use proper HTML syntax!
In our second echo statement we use echo to write a valid Header 5 HTML statement. To do this we simply put the <h5> at the beginning of the string and closed it at the end of the string. Just because you're using PHP to make web pages does not mean you can forget about HTML syntax!

Careful When Echoing Quotes!

It is pretty cool that you can output HTML with PHP. However, you must be careful when using HTML code or any other string that includes quotes! Echo uses quotes to define the beginning and end of the string, so you must use one of the following tactics if your string contains quotations:
  • Don't use quotes inside your string
  • Escape your quotes that are within the string with a backslash. To escape a quote just place a backslash directly before the quotation mark, i.e. \"
  • Use single quotes (apostrophes) for quotes inside your string.
See our example below for the right and wrong use of echo:

PHP Code:

<?php
// This won't work because of the quotes around specialH5!
echo "<h5 class="specialH5">I love using PHP!</h5>";  

// OK because we escaped the quotes!
echo "<h5 class=\"specialH5\">I love using PHP!</h5>";  

// OK because we used an apostrophe '
echo "<h5 class='specialH5'>I love using PHP!</h5>";  
?>
If you want to output a string that includes quotations, either use an apostrophe ( ' ) or escape the quotations by placing a backslash in front of it ( \" ). The backslash will tell PHP that you want the quotation to be used within the string and NOT to be used to end echo's string.

Echoing Variables

Echoing variables is very easy. The PHP developers put in some extra work to make the common task of echoing all variables nearly foolproof! No quotations are required, even if the variable does not hold a string. Below is the correct format for echoing a variable.

PHP Code:

<?php
$my_string = "Hello Bob.  My name is: ";
$my_number = 4;
$my_letter = a;
echo $my_string;
echo $my_number;
echo $my_letter;
?>

Display:

Hello Bob. My name is: 4a

Echoing Variables and Text Strings

You can also place variables inside of double-quoted strings (e.g. "string here and a $variable"). By putting a variable inside the quotes (" ") you are telling PHP that you want it to grab the string value of that variable and use it in the string. The example below shows an example of this cool feature.

PHP Code:

<?php
$my_string = "Hello Bob.  My name is: ";
echo "$my_string Bobettta <br />";
echo "Hi, I'm Bob.  Who are you? $my_string <br />";
echo "Hi, I'm Bob.  Who are you? $my_string Bobetta";
?>

Display:

Hello Bob. My name is: Bobetta
Hi, I'm Bob. Who are you? Hello Bob. My name is:
Hi, I'm Bob. Who are you? Hello Bob. My name is: Bobetta
By placing variables inside a string you can save yourself some time and make your code easier to read, though it does take some getting used to. Remember to use double-quotes, single-quotes will not grab the value of the string. Single-quotes will just output the variable name to the string, like )$my_string), rather than (Hello Bob. My name is: ).

PHP Echo - Not a Function

Echo is not a function, rather it is a language construct. When you use functions in PHP, they have a very particular form, which we will be going over later. For now, just know that echo is a special tool that you'll come to know and love!

PHP Variables (PHP Tutorial part 4)

১১/২২/২০১১ ০৪:২৫:০০ AM | , | 0 comments »

If you have never had any programming, Algebra, or scripting experience, then the concept of variables might be a new concept to you. A detailed explanation of variables is beyond the scope of this tutorial, but we've included a refresher crash course to guide you.

A variable is a means of storing a value, such as text string "Hello World!" or the integer value 4. A variable can then be reused throughout your code, instead of having to type out the actual value over and over again. In PHP you define a variable with the following form:
  • $variable_name = Value;
If you forget that dollar sign at the beginning, it will not work. This is a common mistake for new PHP programmers!
Note: Also, variable names are case-sensitive, so use the exact same capitalization when using a variable. The variables $a_number and $A_number are different variables in PHP's eyes.

A Quick Variable Example

Say that we wanted to store the values that we talked about in the above paragraph. How would we go about doing this? We would first want to make a variable name and then set that equal to the value we want. See our example below for the correct way to do this.

PHP Code:

<?php
$hello = "Hello World!";
$a_number = 4;
$anotherNumber = 8;
?>

Note for programmers: PHP does not require variables to be declared before being initialized.

PHP Variable Naming Conventions

There are a few rules that you need to follow when choosing a name for your PHP variables.
  • PHP variables must start with a letter or underscore "_".
  • PHP variables may only be comprised of alpha-numeric characters and underscores. a-z, A-Z, 0-9, or _ .
  • Variables with more than one word should be separated with underscores. $my_variable
  • Variables with more than one word can also be distinguished with capitalization. $myVariable

PHP Syntax (PHP Tutorial part 3)

১১/২২/২০১১ ০৪:২৩:০০ AM | , | 0 comments »

Before we talk about PHP's syntax, let us first define what syntax is referring to.
  • Syntax - The rules that must be followed to write properly structured code.
PHP's syntax and semantics are similar to most other programming languages (C, Java, Perl) with the addition that all PHP code is contained with a tag, of sorts. All PHP code must be contained within the following...

PHP Code:

<?php
?>

or the shorthand PHP tag that requires shorthand support to be enabled
on your server...

<?
?>
If you are writing PHP scripts and plan on distributing them, we suggest that you use the standard form (which includes the ?php) rather than the shorthand form. This will ensure that your scripts will work, even when running on other servers with different settings.

How to Save Your PHP Pages

If you have PHP inserted into your HTML and want the web browser to interpret it correctly, then you must save the file with a .php extension, instead of the standard .html extension. So be sure to check that you are saving your files correctly. Instead of index.html, it should be index.php if there is PHP code in the file.

Example Simple HTML & PHP Page

Below is an example of one of the easiest PHP and HTML page that you can create and still follow web standards.

PHP and HTML Code:

<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>

Display:

Hello World!
If you save this file (e.g. helloworld.php) and place it on PHP enabled server and load it up in your web browser, then you should see "Hello World!" displayed. If not, please check that you followed our example correctly.
We used the PHP command echo to write "Hello World!" and we will be talking in greater depth about how echo is special later on in this tutorial.

The Semicolon!

As you may or may not have noticed in the above example, there was a semicolon after the line of PHP code. The semicolon signifies the end of a PHP statement and should never be forgotten. For example, if we repeated our "Hello World!" code several times, then we would need to place a semicolon at the end of each statement.

PHP and HTML Code:

<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<?php
echo "Hello World! ";
echo "Hello World! ";
echo "Hello World! ";
echo "Hello World! ";
echo "Hello World! ";
?>
</body>
</html>

Display:

Hello World! Hello World! Hello World! Hello World! Hello World!

White Space

As with HTML, whitespace is ignored between PHP statements. This means it is OK to have one line of PHP code, then 20 lines of blank space before the next line of PHP code. You can also press tab to indent your code and the PHP interpreter will ignore those spaces as well.

PHP and HTML Code:

<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<?php
echo "Hello World!";        



 echo "Hello World!";


?>
</body>
</html>

Display:

Hello World!Hello World!
This is perfectly legal PHP code.

PHP Necessary Setup (PHP Tutorial part 2)

১১/২২/২০১১ ০৪:২২:০০ AM | , | 0 comments »

To begin working with PHP you must first have access to either of the following:
  • A web hosting account that supports the use of PHP web pages and grants you access to MySQL databases. If you do not have a host, but are interested in signing up for one, we recommend that you first read our Web Host Guide to educate yourself about web hosting and avoid getting ripped off.
  • Have PHP and MySQL installed on your own computer. Read this lesson thorougly for more information on installing PHP.
Although MySQL is not absolutely necessary to use PHP, MySQL and PHP are wonderful complements to one another and some topics covered in this tutorial will require that you have MySQL access.

Installing PHP

For those who are experienced enough to do this yourself, simply head over to PHP.net - Downloads and download the most recent version of PHP.
However, if you are like most of us, you will most likely want to follow a guide to installing PHP onto your computer. These guides are kindly provided by PHP.net based on the operating system that you are using.

Installing MySQL

As we mentioned before, MySQL is not a requirement to use PHP, however they often go hand in hand.
Visit MySQL's MySQL Installation Guide for help on installing MySQL.

PHP Installation Troubles

If you have any installation troubles you should visit Tizag's popular PHP forum and ask for help!

PHP Introduction (PHP Tutorial part 1)

১১/২২/২০১১ ০৪:১৮:০০ AM | , | 0 comments »

PHP Tutorial - Learn PHP

If you want to learn the basics of PHP, then you've come to the right place. The goal of this tutorial is to teach you the basics of PHP so that you can:
  • Customize PHP scripts that you download, so that they better fit your needs.
  • Begin to understand the working model of PHP, so you may begin to design your own PHP projects.
  • Give you a solid base in PHP, so as to make you more valuable in the eyes of future employers.
PHP stands for PHP Hypertext Preprocessor.

PHP - What is it?

Taken directly from PHP's home, PHP.net, "PHP is an HTML-embedded scripting language. Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly."
This is generally a good definition of PHP. However, it does contain a lot of terms you may not be used to. Another way to think of PHP is a powerful, behind the scenes scripting language that your visitors won't see!
When someone visits your PHP webpage, your web server processes the PHP code. It then sees which parts it needs to show to visitors(content and pictures) and hides the other stuff(file operations, math calculations, etc.) then translates your PHP into HTML. After the translation into HTML, it sends the webpage to your visitor's web browser.

PHP - What's it do?

It is also helpful to think of PHP in terms of what it can do for you. PHP will allow you to:
  • Reduce the time to create large websites.
  • Create a customized user experience for visitors based on information that you have gathered from them.
  • Open up thousands of possibilities for online tools. Check out PHP - HotScripts for examples of the great things that are possible with PHP.
  • Allow creation of shopping carts for e-commerce websites.

What You Should Know

Before starting this tutorial it is important that you have a basic understanding and experience in the following:
  • HTML - Know the syntax and especially HTML Forms.
  • Basic programming knowledge - This isn't required, but if you have any traditional programming experience it will make learning PHP a great deal easier.

Tutorial Overview

This tutorial is aimed at the PHP novice and will teach you PHP from the ground up. If you want a drive-through PHP tutorial this probably is not the right tutorial for you.
Remember, you should not try to plow through this tutorial in one sitting. Read a couple lessons, take a break, then do some more after the information has had some time to sink in.

Ever wonder how you could change the contents of an HTML element? Maybe you'd like to replace the text in a paragraph to reflect what a visitor has just selected from a drop down box. By manipulating an element's innerHtml you'll be able to change your text and HTML as much as you like.

Changing Text with innerHTML

Each HTML element has an innerHTML property that defines both the HTML code and the text that occurs between that element's opening and closing tag. By changing an element's innerHTML after some user interaction, you can make much more interactive pages.
However, using innerHTML requires some preparation if you want to be able to use it easily and reliably. First, you must give the element you wish to change an id. With that id in place you will be able to use the getElementById function, which works on all browsers.
After you have that set up you can now manipulate the text of an element. To start off, let's try changing the text inside a bold tag.

JavaScript Code:

<script type="text/javascript">
function changeText(){
 document.getElementById('boldStuff').innerHTML = 'Fred Flinstone';
}
</script>
<p>Welcome to the site <b id='boldStuff'>dude</b> </p> 
<input type='button' onclick='changeText()' value='Change Text'/>

Display:

Welcome to the site dude
You now know how to change the text in any HTML element, but what about changing the text in an element based on user input? Well, if we combine the above knowledge with a text input...

Updating Text Based on User Input

By adding a Text Input, we can take to updating our bold text with whatever the user types into the text input. Note: We updated the function a bit and set the id to boldStuff2.

JavaScript Code:

<script type="text/javascript">
function changeText2(){
 var userInput = document.getElementById('userInput').value;
 document.getElementById('boldStuff2').innerHTML = userInput;
}
</script>
<p>Welcome to the site <b id='boldStuff2'>dude</b> </p> 
<input type='text' id='userInput' value='Enter Text Here' />
<input type='button' onclick='changeText2()' value='Change Text'/>

Display:

Welcome to the site dude

Changing HTML with innerHTML

You can also insert HTML into your elements in the exact same way. Let's say we didn't like the text that was displayed in our paragraph and wanted to updated it with some color. The following code will take the old black text and make it bright white. The only thing we're doing different here is inserting the html element span to change the color.

JavaScript Code:

<script type="text/javascript">
function changeText3(){
 var oldHTML = document.getElementById('para').innerHTML;
 var newHTML = "<span style='color:#ffffff'>" + oldHTML + "</span>";
 document.getElementById('para').innerHTML = newHTML;
}
</script>
<p id='para'>Welcome to the site <b id='boldStuff3'>dude</b> </p> 
<input type='button' onclick='changeText3()' value='Change Text'/>

Display:

Welcome to the site dude
This was a pretty simple example for changing the HTML of an element. All we did was take the old text that was in the paragraph tag and surround it in a span tag to change the color. However, there are many more things you can do by changing an element's HTML, so don't forget this useful tool!

Have you ever tried to use JavaScript to do some form validation? Did you have any trouble using JavaScript to grab the value of your text field? There's an easy way to access any HTML element, and it's through the use of id attributes and the getElementById function.

JavaScript document.getElementById

If you want to quickly access the value of an HTML input give it an id to make your life a lot easier. This small script below will check to see if there is any text in the text field "myText". The argument that getElementById requires is the id of the HTML element you wish to utilize.

JavaScript Code:

<script type="text/javascript">
function notEmpty(){
 var myTextField = document.getElementById('myText');
 if(myTextField.value != "")
  alert("You entered: " + myTextField.value)
 else
  alert("Would you please enter some text?")  
}
</script>
<input type='text' id='myText' />
<input type='button' onclick='notEmpty()' value='Form Checker' />

Display:

document.getElementById returned a reference to our HTML element myText. We stored this reference into a variable, myTextField, and then used the value property that all input elements have to use to grab the value the user enters.
There are other ways to accomplish what the above script does, but this is definitely a straight-forward and browser-compatible approach.

Things to Remember About getElementById

When using the getElementById function, you need to remember a few things to ensure that everything goes smoothly. You always need to remember that getElementById is a method (or function) of the document object. This means you can only access it by using document.getElementById.
Also, be sure that you set your HTML elements' id attributes if you want to be able to use this function. Without an id, you'll be dead in the water.
If you want to access the text within a non-input HTML element, then you are going to have to use the innerHTML property instead of value. The next lesson goes into more detail about the uses of innerHTML.


Comparing strings in JavaScript is quite easy, as long as you know about the equals operator and the JavaScript If Statement. This is all you need to know to find out if two strings of your choosing are equal.

Comparing one String to another String

Below we have created a fake authentication system and use an if statement to see if the user's name will grant them access to a special message.

JavaScript Code:

<script type="text/javascript">
var username = "Agent006";
if(username == "Agent007")
 document.write("Welcome special agent 007"); 
else
 document.write("Access Denied!"); 
document.write("<br /><br />Would you like to try again?<br /><br />");

// User enters a different name
username = "Agent007";
if(username == "Agent007")
 document.write("Welcome special agent 007"); 
else
 document.write("Access Denied!"); 

</script>

Display:

Access Denied!

Would you like to try again?

Welcome special agent 007
Be sure you realize that when you are comparing one string to another, you use two equals operators "==" instead of just one "=". When you use two equals operators, it means you are comparing two values.
In this case, the English translation of our program would be: "If username is equal to Agent007, then print out a welcome message; otherwise, access is denied."

Case Insensitive String Compare

Above, we used a case sensitive compare, meaning that if the capitalization wasn't exactly the same in both strings, the if statement would fail. If you would like to just check that a certain word is entered, without worrying about the capitalization, use the toLowerCase function.

JavaScript Code:

<script type="text/javascript">
var username = "someAgent";
if(username == "SomeAgent")
 document.write("Welcome special agent"); 
else
 document.write("Access Denied!"); 
 
// Now as case insensitive
document.write("<br /><br />Let's try it with toLowerCase<br /><br />");
if(username.toLowerCase() == "SomeAgent".toLowerCase())
 document.write("Welcome special agent"); 
else
 document.write("Access Denied!"); 
</script>

Display:

Access Denied!

Let's try it with toLowerCase

Welcome special agent
By converting both strings to lowercase, we were able to remove the problem of it failing to find a match when the capitalization was slightly off. In this case, the "s" was capitalized in the username, but not capitalized in our if statement check.

Ever want to find something in one of your JavaScript strings? Maybe even start your search halfway through the string? Well you're in luck! The string function indexOf lets you supply one required argument (the search query) and one optional argument (the offset) for all your simple searching needs.

If you are looking for a more powerful search feature, you should check out JavaScript's string search function, which has support for regular expressions, but not offsets.

String indexOf Function

As we mentioned above, indexOf has two arguments, with the second one being optional:
  1. SearchString - What you would like to search for.
  2. Offset (optional) - How far into the string you would like the search to begin. If you want to search the whole string, omit this argument.

indexOf Function Example

To start off with, we will be finding the position of the "www" in a typical URL string. The indexOf function will return the location of the first match that it encounters.

JavaScript Code:

<script type="text/javascript">
var aURL = "http://www.tizag.com/";
var aPosition = aURL.indexOf("www");

document.write("The position of www  =  " + aPosition); 
</script>

Display:

The position of www = 7
If you'd like to follow along with how this function does it's counting, here's a complete breakdown:
  • h - 0 - no match
  • t - 1 - no match
  • t - 2 - no match
  • p - 3 - no match
  • : - 4 - no match
  • / - 5 - no match
  • / - 6 - no match
  • w - 7 - maybe match
  • w - 8 - maybe match
  • w - 9 - It's a match, return the position of the start of the match (7).
Let's see what happens when we add another www to the URL string to see if this function gets confused or not.

JavaScript Code:

<script type="text/javascript">
var aURL = "http://www.tizag.com/www.html";
var aPosition = aURL.indexOf("www");

document.write("The position of www  =  " + aPosition); 

</script>

Display:

The position of www = 7
Looks like it returned the position of the first "www", just as we expected, so there are no surprises in this function. However, what would we do if we wanted to find the second "www"? Well, we'd have to use an offset, for starters.

indexOf Function Offset Example

If we use the indexOf function to find the first "www", then we can use that position + 1 as a way to skip the first "www" and find the second.

JavaScript Code:

<script type="text/javascript">
var aURL = "http://www.tizag.com/www.html";
var aPosition = aURL.indexOf("www");
var secondPos = aURL.indexOf("www", aPosition + 1);

document.write("The position of www  =  " + aPosition); 
document.write("<br />The position of the second www  =  " + secondPos); 

</script>

Display:

The position of www = 7
The position of the second www = 21
By using an offset of 8 (7 + 1), we were able to skip the first "www" to instead find the second. In case you're interested in what the function was actually looking at after we gave an offset, we have it below:
  • ww.tizag.com/www.html
There are only 2 w's left at the beginning of the string, due to the offset, making it impossible for a match to be found at the first set of "www".

JavaScript's String Object has a handy function that lets you replace words that occur within the string. This comes in handy if you have a form letter with a default reference of "username". With the replace function you could grab get the person's name with an HTML form or JavaScript prompt and then replace all occurrences of "username" with the value that they entered.

String Replace Function

The string replace function has two arguments:
  1. SearchFor - What word is going to be replaced. This can be a string or a regular expression.
  2. ReplaceText - What the word will be replaced with. This needs to be a string.
replace returns the new string with the replaces, but if there weren't any words to replace, then the original string is returned.

Replace Function: String Replace

To start off with, let's just search for a string and replace it with the visitor's name. The first argument is what we are searching for, and the second argument is what we are going to replace.

JavaScript Code:

<script type="text/javascript">
var visitorName = "Chuck";
var myOldString = "Hello username! I hope you enjoy your stay username.";
var myNewString = myOldString.replace("username", visitorName);

document.write("Old string =  " + myOldString); 
document.write("<br />New string = " + myNewString);

</script>

Display:

Old string = Hello username! I hope you enjoy your stay username.
New string = Hello Chuck! I hope you enjoy your stay username.
Notice that only the first occurrence of "username" was replaced. This is the drawback to using a string as your searchFor argument. But don't worry you can replace all occurrences of "username" if you decide to use regular expressions.

Replace Function: Regular Expression

Let's do the exact same replace, except this time, we'll use a a regular expression instead of a string. The only change we need to make is to surround our searchFor word with slashes / / instead of quotations " ".

JavaScript Code:

<script type="text/javascript">
var visitorName = "Chuck";
var myOldString = "Hello username! I hope you enjoy your stay username.";
var myNewString = myOldString.replace(/username/, visitorName);

document.write("Old string =  " + myOldString); 
document.write("<br />New string = " + myNewString);

</script>

Display:

Old string = Hello username! I hope you enjoy your stay username.
New string = Hello Chuck! I hope you enjoy your stay username.
Darn! No luck. We've still only replaced the first "username" with Chuck instead of all of them. What's the solution to our problem? The answer is enabling the global property for our regular expression.

Replace Function: Global Regular Expression

By enabling the global property of our regular expression, we can go from replacing one match at a time to replacing all matches at once. To enable the global property, just put a "g" at the end of the regular expression.

JavaScript Code:

<script type="text/javascript">
var visitorName = "Chuck";
var myOldString = "Hello username! I hope you enjoy your stay username.";
var myNewString = myOldString.replace(/username/g, visitorName);

document.write("Old string =  " + myOldString); 
document.write("<br />New string = " + myNewString);

</script>

Display:

Old string = Hello username! I hope you enjoy your stay username.
New string = Hello Chuck! I hope you enjoy your stay Chuck.
Finally we've succeeded! Remember that if you just want to replace one word, you should use a string or normal regular expression as your searchFor parameter. However, if you want to replace everything, be sure to write a regular expression and append a little g at the end!

Knowing if something is or isn't in a string can be very important. If you have an online forum and don't want people to be able to create usernames that include swear words, you can use the search function to find bad words in usernames and reject them if any were found.

String Search Function

This string function takes a regular expression and then examines that string to see if there are any matches for that expression. If there is a match , it will return the position in the string where the match was found. If there isn't a match, it will return -1. We won't be going into great depth about regular expressions, but we will show you how to search for words in a string.

Search Function Regular Expression

The most important thing to remember when creating a regular expression is that it must be surrounded with slashes /regular expression/. With that knowledge let's search a string to see if a common name "Alex" is inside it.

JavaScript Code:

<script type="text/javascript">
var myRegExp = /Alex/;
var string1 = "Today John went to the store and talked with Alex.";
var matchPos1 = string1.search(myRegExp);

if(matchPos1 != -1)
 document.write("There was a match at position " + matchPos1); 
else
 document.write("There was no match in the first string");

 
</script>

Display:

There was a match at position 45
Notice that our regular expression was just the name "Alex". The search function then used this name to see if "Alex" existed in string1. A match was found, and the position of the match (45), was returned.

String Search Function: Alternative Searches

Another basic tool for regular expressions is the pipe character "|" (it's below the Backspace key on standard keyboards) which allows you to search for alternative words /RegExp1|RegExp2/. Instead of just searching for just one word, we can now use the pipe character to search for multiple words.

JavaScript Code:

<script type="text/javascript">
var myRegExp = /Alex|John/;
var string1 = "Today John went to the store and talked with Alex.";
var matchPos1 = string1.search(myRegExp);

if(matchPos1 != -1)
 document.write("There was a match at position " + matchPos1); 
else
 document.write("There was no match in the first string");

 
</script>

Display:

There was a match at position 6
Notice that our regular expression had two names: Alex and John. The search function then used these names to try to find the first occurrence in the string string1. John came before Alex in our string, so its position (6), was returned.
Let's look at a couple more advanced examples.

Advanced Search Function Examples

The following examples play around with the names a little so you can clearly see how the search function operates.

JavaScript Code:

<script type="text/javascript">
var myRegExp1 = /Tom|Jan|Alex/;
var string1 = "John went to the store and talked with Alexandra today.";
var matchPos1 = string1.search(myRegExp1);

if(matchPos1 != -1)
 document.write("The first string found a match at " + matchPos1);
else
 document.write("No match was found in the first string"); 

var myRegExp2 = /Tom|Jan|Alex /;
var string2 = "John went to the store and talked with Alexandra today.";
var matchPos2 = string2.search(myRegExp2);
if(matchPos2 != -1)
 document.write("<br />The second string found a match at " + matchPos2); 
else
 document.write("<br />No match was found in the second string");
 
var myRegExp3 = /Tom|Jan|Alexandra/;
var string3 = "John went to the store and talked with Alexandra today.";
var matchPos3 = string3.search(myRegExp3);
if(matchPos3 != -1)
 document.write("<br />The third string found a match at " + matchPos3); 
else
 document.write("<br />No match was found in the third string");

var myRegExp4 = /Tom|Jan|Alexandra/;
var string4 = "John went to the store and talked with Alex today.";
var matchPos4 = string4.search(myRegExp4);
if(matchPos4 != -1)
 document.write("<br />The fourth string found a match at " + matchPos4); 
else
 document.write("<br />No match was found in the fourth string");
</script>

Display:

The first string found a match at 39
No match was found in the second string
The third string found a match at 39
No match was found in the fourth string
In the first search, a match was found. This is because our search didn't specify that the name had to be exactly Alex, and because the name Alexandra contains "Alex", a match was found.
In the second search, we fixed this by adding a space after the name Alex to make our search for "Alex ", and no match was found.
In the third search, we changed our expression to include "Alexandra" and found a match.
In the fourth and final search, we changed our string to include "Alex" and we didn't find a match.

The ability to split up a string into separate chunks has been supported in many programming languages, and it is available in JavaScript as well. If you have a long string like "Bobby Susan Tracy Jack Phil Yannis" and want to store each name separately, you can specify the space character " " and have the split function create a new chunk every time it sees a space.

Split Function: Delimiter

The space character " " we mentioned will be our delimiter and it is used by the split function as a way of breaking up the string. Every time it sees the delimiter we specified, it will create a new element in an array. The first argument of the split function is the delimiter.

Simple Split Function Example

Let's start off with a little example that takes a string of numbers and splits when it sees the number 5. That means the delimiter for this example is 5. Notice that the split function returns an array that we store into mySplitResult.

JavaScript Code:

<script type="text/javascript">
var myString = "123456789";

var mySplitResult = myString.split("5");

document.write("The first element is " + mySplitResult[0]); 
document.write("<br /> The second element is  " + mySplitResult[1]); 
</script>

Display:

The first element is 1234
The second element is 6789
Make sure you realize that because we chose the 5 to be our delimiter, it is not in our result. This is because the delimiter is removed from the string and the remaining characters are separated by the chasm of space that the 5 used to occupy.

Larger Split Function Example

Below we have created a split example to illustrate how this function works with many splits. We have created a string with numbered words zero through four. The delimiter in this example will be the space character " ".

JavaScript Code:

<script type="text/javascript">
var myString = "zero one two three four";

var mySplitResult = myString.split(" ");

for(i = 0; i < mySplitResult.length; i++){
 document.write("<br /> Element " + i + " = " + mySplitResult[i]); 
}
</script>

Display:


Element 0 = zero
Element 1 = one
Element 2 = two
Element 3 = three
Element 4 = four

Advanced scripters will often need to know how long a JavaScript string is. For example, if a webdeveloper was creating a submission form that required the username to be no longer than 20 characters, then she would need to check the length of the string before allowing the user to submit data.

String Length Property

The length property returns the number of characters that are in a string, using an integer. Below is the basic code for accessing this property.

JavaScript Code:

<script type="text/javascript">
var myString = "123456";

var length = myString.length;

document.write("The string is this long: " + length);

// Same thing, but using the property inside the write function
document.write("<br />The string is this long: " + myString.length);

</script>

Display:

The string is this long: 6
The string is this long: 6

String Changed? Length Might Change

If you were to reference the length property after concatenating (adding) some characters to the string, then the length property will reflect these changes. Think of this as a friendly reminder to only check the length of the string after you are sure it isn't going to be changed.

JavaScript Code:

<script type="text/javascript">
var myString = "123456";
document.write("The string is this long: " + myString.length);

myString = myString + "7890";
document.write("<br />The string is now this long: " + myString.length);

</script>

Display:

The string is this long: 6
The string is now this long: 10

This may be old news to you, but inside every JavaScript string are several functions that are just waiting to do your bidding. This is because strings in JavaScript are actually objects with a bunch of properties and functions (also called methods) that can be accessed in the following general way:

Pseudo JavaScript Code:

<script type="text/javascript">
var myString = "Hello Thur!";

//This is how you would access a property
var myProperty = myString.property;

//This is how you would access a function
var myFunctionResult = myString.function(argument1, argument2);
</script>
As you can see, the most important part to accessing string properties and functions is to first create them. In this case, myString was our guinea pig.

What's a String Property?

A property is just some basic information about the object. For example, a string object has a length property which stores the number of characters in the string.

What's a String Function?

The string's functions are useful for finding out more about your string. For example, the string function split lets you take a string and chop it into pieces whenever characters that you supply, appear.
It is important to note that these functions do not actually change the string itself. Rather, they return new strings that you can store for use elsewhere. In our example, we stored the result of our make-believe function into myFunctionResult.

String Functions and Properties

The following lessons will teach you how to manipulate, count, reorder, replace, search and do just about anything else to your JavaScript strings. These advanced topics will open up a whole new world of choices for the dynamic webpages you have yet to build!

JavaScript Void 0 (JavaScript Tutorial part 25)

১১/২১/২০১১ ১২:৪৫:০০ AM | , | 0 comments »

Hyperlinks like this one entice visitors to click because they know clicking it will lead them to a new page. However, sometimes when you are making a script, you would like to add functionality to your website that lets a hyperlink to be clicked and perform a useful action like update the sums on the webpage, without loading a new page.

It's these types of programming solutions that will utilize the JavaScript Void 0 programming tool. This lesson will teach you some of the reasons to use the JavaScript Void 0programming strategy in your scripts.

Directly Executing JavaScript in a Browser

Web browsers allow you to execute JavaScript statements directly by entering JavaScript code into the browser's URL text field. All you need to do is place a JavaScript: before your code to inform the browser you wish to run JavaScript. You can play around with this right now by typing something like
  • JavaScript:alert("I'm learning at Tizag.com")
into the browser's URL text field and pressing Enter.
This is useful to you, the JavaScript scripter, because you can now set your hyperlinks's href attribute equal to a JavaScript statement! This means you can remove the hyperlink's ability to load a new page and reprogram it to do your "complete some actions directly on this page" bidding.
This practice can be seen in services like Gmail (Google Email) which does a great deal of interaction with hyperlinks, but has very few new pages loading. Here is an example link that does not load a new webpage.

JavaScript Code:

<a href="javascript: alert('News Flash!')">News Flash</a>

Display:

This is interesting to learn, but it isn't much more than a gimmick. The true power of direct URL JavaScript statements is only unleashed when you use it to return a value. This is where void 0 comes into play.

JavaScript Void 0 Explanation

Web browsers will try and take whatever is used as a URL and load it. The only reason we can use a JavaScript Alert statement without loading a new page is because alert is a function that returns a null value. This means that when the browser attempts to load a new page it sees null and has nothing to load.
The important thing to notice here is that if you ever do use a JavaScript statement as the URL that returns a value, the browser will attempt to load a page. To prevent this unwanted action, you need to use the void function on such statement, which will always return null and never load a new page.

Simple JavaScript Void 0 Simple Example

void is an operator that is used to return a null value so the browser will not be able to load a new page. An important thing to note about the void operator is that it requires a value and cannot be used by itself. Here is a simple way to use void to cancel out the page load.

JavaScript Code:

<a href="javascript: void(0)">I am a useless link</a>

Display:

Simple JavaScript Void 0 Useful Example

This example shows how you would return a value using the void operator. myNum is a variable that we set to the value 10. We then use the same variable myNum in an alertoperation.

JavaScript Code:

<a href="javascript: void(myNum=10);alert('myNum = '+myNum)">
Set myNum Please</a>

Display:

JavaScript Form Validation (JavaScript Tutorial part 24)

১১/২১/২০১১ ১২:৪২:০০ AM | , | 0 comments »

There's nothing more troublesome than receiving orders, guestbook entries, or other form submitted data that are incomplete in some way. You can avoid these headaches once and for all with JavaScript's amazing way to combat bad form data with a technique called "form validation".

The idea behind JavaScript form validation is to provide a method to check the user entered information before they can even submit it. JavaScript also lets you display helpful alerts to inform the user what information they have entered incorrectly and how they can fix it. In this lesson we will be reviewing some basic form validation, showing you how to check for the following:
  • If a text input is empty or not
  • If a text input is all numbers
  • If a text input is all letters
  • If a text input is all alphanumeric characters (numbers & letters)
  • If a text input has the correct number of characters in it (useful when restricting the length of a username and/or password)
  • If a selection has been made from an HTML select input (the drop down selector)
  • If an email address is valid
  • How to check all above when the user has completed filling out the form
This lesson is a little long, but knowing how to implement these form validation techniques is definitely worth the effort on your part. Remember to check out Tizag's HTML forms lesson if you need to brush up on your form knowledge.

Form Validation - Checking for Non-Empty

This has to be the most common type of form validation. You want to be sure that your visitors enter data into the HTML fields you have "required" for a valid submission. Below is the JavaScript code to perform this basic check to see if a given HTML input is empty or not.

JavaScript Code:

// If the length of the element's string is 0 then display helper message
function notEmpty(elem, helperMsg){
 if(elem.value.length == 0){
  alert(helperMsg);
  elem.focus(); // set the focus to this input
  return false;
 }
 return true;
}
The function notEmpty will check to see that the HTML input that we send it has something in it. elem is a HTML text input that we send this function. JavaScriptstrings have built in properties, one of which is the length property which returns the length of the string. The chunk of code elem.value will grab the string inside the input and by adding on length elem.value.length we can see how long the string is.
As long as elem.value.length isn't 0 then it's not empty and we return true, otherwise we send an alert to the user with a helperMsg to inform them of their error and return false.

Working Example:

<script type='text/javascript'>
function notEmpty(elem, helperMsg){
 if(elem.value.length == 0){
  alert(helperMsg);
  elem.focus();
  return false;
 }
 return true;
}
</script>
<form>
Required Field: <input type='text' id='req1'/>
<input type='button' 
 onclick="notEmpty(document.getElementById('req1'), 'Please Enter a Value')"
 value='Check Field' />
</form>

Display:

Required Field:

Form Validation - Checking for All Numbers

If someone is entering a credit card, phone number, zip code, similar information you want to be able to ensure that the input is all numbers. The quickest way to check if an input's string value is all numbers is to use a regular expression /^[0-9]+$/ that will only match if the string is all numbers and is at least one character long.

JavaScript Code:

// If the element's string matches the regular expression it is all numbers
function isNumeric(elem, helperMsg){
 var numericExpression = /^[0-9]+$/;
 if(elem.value.match(numericExpression)){
  return true;
 }else{
  alert(helperMsg);
  elem.focus();
  return false;
 }
}
What we're doing here is using JavaScript existing framework to have it do all the hard work for us. Inside each string is a function called match that you can use to see if the string matches a certain regular expression. We accessed this function like so: elem.value.match(expressionhere).
We wanted to see if the input's string was all numbers so we made a regular expression to check for numbers [0-9] and stored it as numericExpression.
We then used the match function with our regular expression. If it is numeric then match will return true, making our if statement pass the test and our function isNumeric will also return true. However, if the expression fails because there is a letter or other character in our input's string then we'll display our helperMsg and return false.

Working Example:

<script type='text/javascript'>
function isNumeric(elem, helperMsg){
 var numericExpression = /^[0-9]+$/;
 if(elem.value.match(numericExpression)){
  return true;
 }else{
  alert(helperMsg);
  elem.focus();
  return false;
 }
}
</script>
<form>
Numbers Only: <input type='text' id='numbers'/>
<input type='button' 
 onclick="isNumeric(document.getElementById('numbers'), 'Numbers Only Please')"
 value='Check Field' />
</form>

Display:

Numbers Only:

Form Validation - Checking for All Letters

This function will be identical to isNumeric except for the change to the regular expression we use inside the match function. Instead of checking for numbers we will want to check for all letters.
If we wanted to see if a string contained only letters we need to specify an expression that allows for both lowercase and uppercase letters: /^[a-zA-Z]+$/ .

JavaScript Code:

// If the element's string matches the regular expression it is all letters
function isAlphabet(elem, helperMsg){
 var alphaExp = /^[a-zA-Z]+$/;
 if(elem.value.match(alphaExp)){
  return true;
 }else{
  alert(helperMsg);
  elem.focus();
  return false;
 }
}

Working Example:

<script type='text/javascript'>
function isAlphabet(elem, helperMsg){
 var alphaExp = /^[a-zA-Z]+$/;
 if(elem.value.match(alphaExp)){
  return true;
 }else{
  alert(helperMsg);
  elem.focus();
  return false;
 }
}
</script>
<form>
Letters Only: <input type='text' id='letters'/>
<input type='button' 
 onclick="isAlphabet(document.getElementById('letters'), 'Letters Only Please')"
 value='Check Field' />
</form>

Display:

Letters Only:

Form Validation - Checking for Numbers and Letters

By combining both the isAlphabet and isNumeric functions into one we can check to see if a text input contains only letters and numbers.

JavaScript Code:

// If the element's string matches the regular expression it is numbers and letters
function isAlphanumeric(elem, helperMsg){
 var alphaExp = /^[0-9a-zA-Z]+$/;
 if(elem.value.match(alphaExp)){
  return true;
 }else{
  alert(helperMsg);
  elem.focus();
  return false;
 }
}

Form Validation - Restricting the Length

Being able to restrict the number of characters a user can enter into a field is one of the best ways to prevent bad data. For example, if you know that the zip code field should only be 5 numbers you know that 2 numbers is not sufficient.
Below we have created a lengthRestriction function that takes a text field and two numbers. The first number is the minimum number of characters and the second is the maximum number of a characters the input can be. If you just want to specify an exact number then send the same number for both minimum and maximum.

JavaScript Code:

function lengthRestriction(elem, min, max){
 var uInput = elem.value;
 if(uInput.length >= min && uInput.length <= max){
  return true;
 }else{
  alert("Please enter between " +min+ " and " +max+ " characters");
  elem.focus();
  return false;
 }
}
Here's an example of this function for a field that requires 6 to 8 characters for a valid username.

Working Example:

<script type='text/javascript'>
function lengthRestriction(elem, min, max){
 var uInput = elem.value;
 if(uInput.length >= min && uInput.length <= max){
  return true;
 }else{
  alert("Please enter between " +min+ " and " +max+ " characters");
  elem.focus();
  return false;
 }
}
</script>
<form>
Username(6-8 characters): <input type='text' id='restrict'/>
<input type='button' 
 onclick="lengthRestriction(document.getElementById('restrict'), 6, 8)"
 value='Check Field' />
</form>

Display:

Username(6-8 characters):

Form Validation - Selection Made

To be sure that someone has actually selected a choice from an HTML select input you can use a simple trick of making the first option as helpful prompt to the user and a red flag to you for your validation code.
By making the first option of your select input something like "Please Choose" you can spur the user to both make a selection and allow you to check to see if the default option "Please Choose" is still selected when the submit the form.

JavaScript Code:

function madeSelection(elem, helperMsg){
 if(elem.value == "Please Choose"){
  alert(helperMsg);
  elem.focus();
  return false;
 }else{
  return true;
 }
}

Working Example:

<script type='text/javascript'>
function madeSelection(elem, helperMsg){
 if(elem.value == "Please Choose"){
  alert(helperMsg);
  elem.focus();
  return false;
 }else{
  return true;
 }
}
</script>
<form>
Selection: <select id='selection'>
<option>Please Choose</option>
<option>CA</option>
<option>WI</option>
<option>XX</option>
</select>
<input type='button' 
 onclick="madeSelection(document.getElementById('selection'), 'Please Choose Something')"
 value='Check Field' />
</form>

Display:

Selection:

Form Validation - Email Validation

And for our grand finale we will be showing you how to check to see if a user's email address is valid. Every email is made up for 5 parts:
  1. A combination of letters, numbers, periods, hyphens, plus signs, and/or underscores
  2. The at symbol @
  3. A combination of letters, numbers, hyphens, and/or periods
  4. A period
  5. The top level domain (com, net, org, us, gov, ...)
Valid Examples:
  • bobby.jo@filltank.net
  • jack+jill@hill.com
  • the-stand@steven.king.com
Invalid Examples:
  • @deleted.net - no characters before the @
  • free!dom@bravehe.art - invalid character !
  • shoes@need_shining.com - underscores are not allowed in the domain name
The regular expression to check for all of this is a little overkill and beyond the scope of this tutorial to explain thoroughly. However, test it out and you'll see that it gets the job done.

JavaScript Code:

function emailValidator(elem, helperMsg){
 var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
 if(elem.value.match(emailExp)){
  return true;
 }else{
  alert(helperMsg);
  elem.focus();
  return false;
 }
}

Working Example:

<script type='text/javascript'>
function emailValidator(elem, helperMsg){
 var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
 if(elem.value.match(emailExp)){
  return true;
 }else{
  alert(helperMsg);
  elem.focus();
  return false;
 }
}
</script>
<form>
Email: <input type='text' id='emailer'/>
<input type='button' 
 onclick="emailValidator1(document.getElementById('emailer'), 'Not a Valid Email')"
 value='Check Field' />
</form>

Display:

Email:

Validating a Form - All at Once

If you've made it this far I commend you, but we're not done yet! The final step is to be able to perform all of these validation steps when the user is ready to submit their data.
Each form has a JavaScript event called onSubmit that is triggered when its submit button is clicked. If this even returns 0 or false then a form cannot be submitted, and if it returns 1 or true it will always be submitted. Wouldn't it be perfect if we could somehow make an if statement that said "If the form is valid submit it (1) else don't submit it (0)"? Well with a master formValidator function we can do just that.
formValidator will be somewhat like a list of checks that we want to do before a form is submitted. But before we can decide what we want to check for, we need to have our form!

HTML Form Code:

<form onsubmit='return formValidator()' >
First Name: <input type='text' id='firstname' /><br />
Address: <input type='text' id='addr' /><br />
Zip Code: <input type='text' id='zip' /><br />
State: <select id='state'>
 <option>Please Choose</option>
 <option>AL</option>
 <option>CA</option>
 <option>TX</option>
 <option>WI</option>
</select><br />
Username(6-8 characters): <input type='text' id='username' /><br />
Email: <input type='text' id='email' /><br />
<input type='submit' value='Check Form' /><br />
</form>
That's a lot of data to verify and the first thing we would probably want to check is that each field was at least filled out. To check for completion we will ensure no fields are empty and that the SELECT field has a selection. Here are the starting pieces of our master validation function formValidator.

JavaScript Code:

function formValidator(){
 // Make quick references to our fields
 var firstname = document.getElementById('firstname');
 var addr = document.getElementById('addr');
 var zip = document.getElementById('zip');
 var state = document.getElementById('state');
 var username = document.getElementById('username');
 var email = document.getElementById('email');
 
 // Check each input in the order that it appears in the form!
 if(isAlphabet(firstname, "Please enter only letters for your name")){
  if(isAlphanumeric(addr, "Numbers and Letters Only for Address")){
   if(isNumeric(zip, "Please enter a valid zip code")){
    if(madeSelection(state, "Please Choose a State")){
     if(lengthRestriction(username, 6, 8)){
      if(emailValidator(email, "Please enter a valid email address")){
       return true;
      }
     }
    }
   }
  }
 }
 
 
 return false;
 
}
The first part of this function is where we create easy references to our HTML inputs using the getElementById function. These quick references will make our next block of code much easier to read!
The second part uses a bunch of embedded if statements to see whether or not each field has the correct type of data. If every single one of those fields we check validates, then we'll return true and the form will be submitted successfully.
However, if just one of those if statements fails then the return false at the end of the function is reached and prevents the form for being submitted.
As you can see this function really does do quite a lot, definitely earning the title of formValidator. Notice how this one function references all of the functions we have covered in this lesson. By placing all of these checks in a central location you make your code easier to read and easier to change around in the future.
Now let's put all the necessary and HTML together and try it out!

All Together Now

Below we have taken the HTML form code and the new function formValidator and plugged in all the other form validation functions taught in this lesson that are referenced in formValidator.

HTML & JavaScript Code:

<script type='text/javascript'>

function formValidator(){
 // Make quick references to our fields
 var firstname = document.getElementById('firstname');
 var addr = document.getElementById('addr');
 var zip = document.getElementById('zip');
 var state = document.getElementById('state');
 var username = document.getElementById('username');
 var email = document.getElementById('email');
 
 // Check each input in the order that it appears in the form!
 if(isAlphabet(firstname, "Please enter only letters for your name")){
  if(isAlphanumeric(addr, "Numbers and Letters Only for Address")){
   if(isNumeric(zip, "Please enter a valid zip code")){
    if(madeSelection(state, "Please Choose a State")){
     if(lengthRestriction(username, 6, 8)){
      if(emailValidator(email, "Please enter a valid email address")){
       return true;
      }
     }
    }
   }
  }
 }
 
 
 return false;
 
}

function notEmpty(elem, helperMsg){
 if(elem.value.length == 0){
  alert(helperMsg);
  elem.focus(); // set the focus to this input
  return false;
 }
 return true;
}

function isNumeric(elem, helperMsg){
 var numericExpression = /^[0-9]+$/;
 if(elem.value.match(numericExpression)){
  return true;
 }else{
  alert(helperMsg);
  elem.focus();
  return false;
 }
}

function isAlphabet(elem, helperMsg){
 var alphaExp = /^[a-zA-Z]+$/;
 if(elem.value.match(alphaExp)){
  return true;
 }else{
  alert(helperMsg);
  elem.focus();
  return false;
 }
}

function isAlphanumeric(elem, helperMsg){
 var alphaExp = /^[0-9a-zA-Z]+$/;
 if(elem.value.match(alphaExp)){
  return true;
 }else{
  alert(helperMsg);
  elem.focus();
  return false;
 }
}

function lengthRestriction(elem, min, max){
 var uInput = elem.value;
 if(uInput.length >= min && uInput.length <= max){
  return true;
 }else{
  alert("Please enter between " +min+ " and " +max+ " characters");
  elem.focus();
  return false;
 }
}

function madeSelection(elem, helperMsg){
 if(elem.value == "Please Choose"){
  alert(helperMsg);
  elem.focus();
  return false;
 }else{
  return true;
 }
}

function emailValidator(elem, helperMsg){
 var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
 if(elem.value.match(emailExp)){
  return true;
 }else{
  alert(helperMsg);
  elem.focus();
  return false;
 }
}
</script>

<form onsubmit='return formValidator()' >
First Name: <input type='text' id='firstname' /><br />
Address: <input type='text' id='addr' /><br />
Zip Code: <input type='text' id='zip' /><br />
State: <select id='state'>
 <option>Please Choose</option>
 <option>AL</option>
 <option>CA</option>
 <option>TX</option>
 <option>WI</option>
</select><br />
Username(6-8 characters): <input type='text' id='username' /><br />
Email: <input type='text' id='email' /><br />
<input type='submit' value='Check Form' />
</form>

Display:

First Name:
Address:
Zip Code:
State:
Username(6-8 characters):
Email: