ColdFusion Mad Libs - Part I

ColdFusion Mad Libs (Part 1 of 2)

Hello ColdFusion people. Here?s a nice little time-waster that you can put up on your site that is sure to amuse your visitors and keep them coming back for more.

For those that may not be aware, Mad Libs were very popular in the late 70?s and early 80?s (yes, I *am* that old). A Mad Lib is a story with certain words omitted. The type of word is specified (eg noun, verb, adjective, etc). One person asks another person (or group of people) to provide those words, and proceeds to fill in the blanks. The result is often amusing (and more often than not, kind of dirty).

If you want to see this in action, check out http://charlie.griefer.com/madlibs_1.cfm.

At it?s most basic, this is a very easy application to create. It requires only two templates?a form (to collect the missing words), and the form?s action page (to display the completed story).

On with the show. This very simple example is going to use the nursery rhyme Jack & Jill to create our Mad Lib:

madlibs_1.cfm:
*****************************************
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>

<html xmlns=
"http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv=
"Content-Type" content="text/html; charset=utf-8" />

<script language="JavaScript" type="text/javascript">
    function validateFields(form) {
                for (var i=0; i<form.elements.length; i++) {
                if (form.elements[i].value == "") {
                    alert('All Fields Are Required!\n\nPlease Fill in Field #' + (parseInt(i) + 1));
                    form.elements[i].focus();
                    return false;
                }
    }
        return true;
    }
</script>

<style type="text/css">
    body, td, input { font-family:verdana; font-size:11px; }
    input { color:#0000cc; }
    .label { font-weight:bold; }
</style>

</head>

<body>


<form action="madlibs_2.cfm" method="post" onsubmit="return validateFields(this);">
<table border="0">
    <tr>
        <td class=
"label">A boy's name:&nbsp;</td>
        <td>
<input type="text" name="ff_1" /></td>
    </tr>
    <tr>
        <td class=
"label">A girl's name:&nbsp;</td>
        <td>
<input type="text" name="ff_2" /></td>
    </tr>
    <tr>
        <td class=
"label">Noun:&nbsp;</td>
        <td>
<input type="text" name="ff_3" /></td>
    </tr>
    <tr>
        <td class=
"label">Verb:&nbsp;</td>
        <td>
<input type="text" name="ff_4" /></td>
    </tr>
    <tr>
        <td class=
"label">A Liquid:&nbsp;</td>
        <td>
<input type="text" name="ff_5" /></td>
    </tr>
    <tr>
        <td class=
"label">Noun:&nbsp;</td>
        <td>
<input type="text" name="ff_6" /></td>
    </tr>
    <tr>
        <td class=
"label">Verb (ending in -ing):&nbsp;</td>
        <td>
<input type="text" name="ff_7" /></td>
    </tr>
    <tr>
        <td>
&nbsp;</td>
        <td>
<input type="submit" value="proceed >>" style="color:#000000;" /></td>
    </tr>
</table>

</form>

</body>
</html>

***************************************

You?ll see that this is a simple form, asking for only 7 values. It includes a simple JavaScript form field validation, which is pretty important. If any fields are left blank, the effect on the next page will not be the effect desired. Although it?s very basic, it does the job. It executes when the form is submitted (see inside the <form> tag the onsubmit=?return validateFields(form);?). If a field is blank, it alerts the user, and places the cursor in the empty field. If you have any questions about the JavaScript form validation, I?m more than happy to answer them in the forums.

That?s about all for page 1. Now onto page 2:

madlibs_2.cfm
***************************************
<cfsilent>

<cfif NOT structKeyExists(form,
'ff_1')>
    <cflocation url=
"madlibs_1.cfm" addtoken="no" />
    <cfabort />
</cfif>

</cfsilent>
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>

<html xmlns=
"http://www.w3.org/1999/xhtml">
<head>
<title>
Untitled</title>
<meta http-equiv=
"Content-Type" content="text/html;charset=utf-8" />

<style type="text/css">
    body { font-family:verdana,arial,helvetica; font-size:11px; }
    b { color:#ff0000; font-variant:small-caps; background-color:#ffffcc; }
    h3 { color:#0000cc; font-size:14px; font-weight:bold; text-decoration:underline; }
    a { color:#0000ff; text-decoration:underline; }
    a:hover { color:#ff0000; text-decoration:none; }
</style>
</head>

<body>

<h3>
Your Mad Lib:</h3>

<cfoutput>
<div style="border:1px ##000000 solid; width:450px; padding:8px;">
<b>#form.ff_1#</b> and <b>#form.ff_2#</b> went up the <b>#form.ff_3#</b> to <b>#form.ff_4#</b> a pail of <b>#form.ff_5#</b>.
<br />
<b>#form.ff_1#</b> fell down and broke his <b>#form.ff_6#</b> and <b>#form.ff_2#</b> came <b>#form.ff_7#</b> after.
</div>
</cfoutput>

<br /><br />


<a href="madlibs_1.cfm">play again</a>

</body>
</html>

****************************************

Also very straightforward. One thing to point out is the <cfsilent> block at the top of the page. This is done because I am writing XHTML compliant code, which stipulates that the very first line must be <?xml version="1.0" encoding="utf-8"?>. Without <cfsilent>, the <cfif> block would generate whitespace, rendering my code non-compliant.

And just what is that <cfif> you ask? That?s checking to make sure that that the user is coming from the form. It?s the same logic as <cfif NOT isDefined(?form.ff_1?)>, but the syntax that I used (<cfif NOT structKeyExists(form, ?ff_1?)>) is much faster. Rather than having to parse a string (which isDefined() must do), the structKeyExists() function can quickly check the form structure to ensure that the key specified is in there. That may be a whole ?nother tutorial. If you?d like to discuss this further, or would like me to elaborate further, either contact me, or post a note on the forums.

The rest of it is straight CF form output. We are simply outputting the various form field values into the story of Jack and Jill, in the appropriate places. It just might end up looking like this:

"PABLO and SHANIA TWAIN went up the STREET to DRINK a pail of BEER. 
PABLO fell down and broke his COMPUTER and SHANIA TWAIN came SQUARE-DANCING after."


That?s it. You?ve can now add Mad Libs to your Web site. Also see part two of this tutorial, which demonstrates how to let the user save the completed Mad Lib to a database. This way your site visitors can browse through past Mad Libs and see how creative (or dirty) others have been J

Enjoy!



All ColdFusion Tutorials By Author: Charlie Griefer (CJ)
  • arrays and structures - part 1
    part one of a three-part tutorial designed to gently introduce you to the world of complex variables.
    Author: Charlie Griefer (CJ)
    Views: 23,026
    Posted Date: Monday, August 11, 2003
  • arrays and structures - part 2
    part two of a three-part tutorial designed to gently introduce you to the world of complex variables.
    Author: Charlie Griefer (CJ)
    Views: 15,823
    Posted Date: Monday, August 11, 2003
  • arrays and structures - part 3
    part three of a three-part tutorial designed to gently introduce you to the world of complex variables.
    Author: Charlie Griefer (CJ)
    Views: 18,690
    Posted Date: Monday, August 11, 2003
  • CF 'Best Practices'
    Some tips and techniques that I've picked up over the years. I don't maintain that these are 'official' or 'absolute'...they are simply my preference and things that have worked for me. I would like to share them here, and leave you to make the decision as to whether or not they fit in your 'code arsenal' :)
    Author: Charlie Griefer (CJ)
    Views: 21,935
    Posted Date: Friday, August 15, 2003
  • CFSCRIPT Intro
    An introductory look at CFSCRIPT. Rules, some basic syntax, and a couple of examples of loops and conditional processing.
    Author: Charlie Griefer (CJ)
    Views: 27,736
    Posted Date: Saturday, January 18, 2003
  • ColdFusion Mad Libs - Part I
    A silly but fun time-waster that you can easily include on your Web site. You might be surprised at how addicting it can become :)
    Author: Charlie Griefer (CJ)
    Views: 17,491
    Posted Date: Thursday, May 29, 2003
  • ColdFusion Mad Libs - Part II
    You've finished the first Mad Libs tutorial, but you feel like there's something missing. Of course there is! You want to be able to save the final output to a database to let your visitors browse through other user's stories. Includes a bad-words filter for the more conservative among us :)
    Author: Charlie Griefer (CJ)
    Views: 14,085
    Posted Date: Thursday, May 29, 2003
  • Dynamic Column Output (Part One)
    Have you ever wanted to display your content in rows of 3 columns? If you ever wanted to specify the number of columns per row within your content, here's the tutorial for you.
    Author: Charlie Griefer (CJ)
    Views: 20,432
    Posted Date: Thursday, May 29, 2003
  • Dynamic Column Output (Part Two)
    This tutorial picks up where the Dynamic Columns tutorial left off, showing you how to not only output your data in a specified number of columns, but how to do it while still publishing well formed HTML.
    Author: Charlie Griefer (CJ)
    Views: 15,935
    Posted Date: Saturday, May 31, 2003
  • Grouping Output in CF
    How to group cfquery output in order to effectively display relational database data. Includes an overview of how to output nested groups as well.
    Author: Charlie Griefer (CJ)
    Views: 18,373
    Posted Date: Tuesday, June 17, 2003
  • Helping users obtain their passwords
    Your site requires your visitors to log in. of course, some of your visitors are going to forget their passwords (ok, most will forget their passwords). You don't want them to have to send you an e-mail, and then wait for a response. They need immediate access.

    This tutorial shows two methods by which you can accomodate them.
    Author: Charlie Griefer (CJ)
    Views: 17,002
    Posted Date: Thursday, August 28, 2003
  • JavaScript Form Validation
    Yes, I know we're a ColdFusion site...but ColdFusion does not live in a vacuum. We have to know SQL, HTML, CSS...and sometimes...JavaScript! This tutorial focuses on using JavaScript (in lieu of cfform) to create client side form validation (and explains why writing your own is better than using ).
    Author: Charlie Griefer (CJ)
    Views: 34,941
    Posted Date: Thursday, August 14, 2003
  • Remote File Management
    Manage text-based files on your server from any Web browser. Create a new file, edit a file, or delete a file. Can be a life saver if you're on the road, and find an error in some of your code that needs a quick fix.
    Author: Charlie Griefer (CJ)
    Views: 17,755
    Posted Date: Tuesday, June 3, 2003
  • Save your visitor's clickstreams
    A nifty little custom tag that will allow you to save a visitor's clickstream through your site, as well as display it back to them (with links). Did I really just say 'nifty'?
    Author: Charlie Griefer (CJ)
    Views: 15,194
    Posted Date: Monday, June 16, 2003
  • to cfqueryparam or not to cfqueryparam
    It's been out there since ColdFusion 4.5...most of us have heard of it...few of us use it. Here are some compelling reasons why you should get into the habit of using the tag.
    Author: Charlie Griefer (CJ)
    Views: 20,903
    Posted Date: Thursday, May 29, 2003