Using jQuery with ColdFusion to handle form field values

Posted on August 25, 2008

More often than not, you’re placing ColdFusion (or any server-side language) code within HTML to set pre-existing values of a form. You can cut down on tons of excess server-side code by setting those values using Javascript. Here are a few examples of how you can use jQuery with ColdFusion to set form values.

What is jQuery?

jQuery is a fast, concise,JavaScript Library that simplifies how you traverse HTML documents, handle events, perform animations, and add Ajax interactions to your web pages.” – jQuery Team

What does that mean?

Let’s say you have this form and you want to populate the text field using Javascript.

<form id="myForm" name="myForm" action="" method="post">
    <input type="text" id="myText" name="myText" value="" />
</form>

The old school way would be to reference the name of the form and the name of the element that you want to manipulate.

document.myForm.myText.value = "Hello world!";

The new school way is to reference only the id of the element you want to manipulate.

document.getElementById("myText").value = "I said, 'Hello World!'";

The way cool and groovy way is to tell jQuery the id of the element and pass the new value to its val() function.

$('#myText').val("*pak* I FEEL GOOD!");

Big deal, they’re all one line.

Ok, so here’s a simple select menu. Let’s add a row of buttons that change the selected option when clicked.

<form id="myForm" name="myForm" action="" method="post">
<select id="mySelect" name="mySelect">
    <option value="0">-- Select --</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>
</form>

The old school way requires us to call the function oldSchool() when we click a button.

<input type="button" onclick="oldSchool('1')" value="Select 1"/> |
<input type="button" onclick="oldSchool('2')" value="Select 2"/> |
<input type="button" onclick="oldSchool('3')" value="Select 3"/>

<script type="text/javascript">
function oldSchool(a) {
    for ( var x = 0; x < document.myForm.mySelect.options.length; x++ ) {
        if ( document.myForm.mySelect.options[x].value == a ) {
            document.myForm.mySelect.options[x].selected = true;
        }
    }
}
</script>

The new school way also requires us to call the function newSchool() when we click a button. You can see that newSchool() is just oldSchool() using getElementById().

<input type="button" onclick="newSchool('1')" value="Select 1"/> |
<input type="button" onclick="newSchool('2')" value="Select 2"/> |
<input type="button" onclick="newSchool('3')" value="Select 3"/>

<script type="text/javascript">
function newSchool(a) {
    for ( var x = 0; x < document.getElementById("mySelect").options.length; x++ ) {
        if ( document.getElementById("mySelect").options[x].value == a ) {
            document.getElementById("mySelect").options[x].selected = true;
        }
    }
}
</script>

But the way cool and groovy way only requires us to click a button.

<input type="button" onclick="$('#mySelect').val('1')" value="Select 1"/> |
<input type="button" onclick="$('#mySelect').val('2')" value="Select 2"/> |
<input type="button" onclick="$('#mySelect').val('3')" value="Select 3"/>

jQuery uses the single function val() to abstract the process needed to select a specific option in a <select> menu, as well as the process needed to change the value of a simple text input.

So how can we take advantage of this using ColdFusion?

If/Else in option tags are the devil

How many times have you run into (or written) code that looks like this?

<select id="mySelect" name="mySelect">
    <option value="0"<cfif form.mySelect eq 0> selected</cfif>>-- Select --</option>
    <option value="1"<cfif form.mySelect eq 1> selected</cfif>>One</option>
    <option value="2"<cfif form.mySelect eq 2> selected</cfif>>Two</option>
    <option value="3"<cfif form.mySelect eq 3> selected</cfif>>Three</option>
</select>

Imagine you’ve got a ton of address forms that all require that a user’s State. I can’t tell you how many applications I’ve inherited where I find the same select menu with 50+ options for states, districts, territories, etc. all hardcoded using if/else to mark the options as selected. Now picture that same code copied onto 20 different forms. Now picture having to update those 20 forms any time you need to add an option.

Yeah, I’m not gonna do that. Not anymore.

Instead, let’s convert this select menu into a reusable bit of code that I can call anywhere I need. Here’s the code for select_module.cfm.

<cfparam name="attributes.fieldName" type="string" default="foo" />
<cfparam name="attributes.selectedValue" type="string" default="" />

<cfoutput>
<select id="#attributes.fieldName#" name="#attributes.fieldName#">
    <option value="">-- Select --</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>

<script type="text/javascript">
    $('###attributes.fieldName#').val('#attributes.selectedValue#');
</script>
</cfoutput>

And here’s the code for page that will call select_module.cfm using cfmodule. Remember that you can call any CFM file as a custom tag using the cf prefix. The only thing is that the file has to be in the same folder or stored in a folder that has been defined as a Custom Tag location in the ColdFusion Administrator. Using cfmodule, you can specify the location of the CFM file you’re going to use which makes it more flexible.

<cfparam name="form.mySelect" type="numeric" default="0" />

<script type="text/javascript" src="/dfwcfug/common/jquery/jquery-1.2.6.min.js"></script>

## Loading a <select> as a <cfmodule>

<form id="myForm" name="myForm" action="" method="post">

<p><input type="text" id="someField" name="someField" /></p>

<cfmodule template="select_module.cfm"
    fieldName="mySelect"
    selectedValue="#form.mySelect#">

<p><input type="submit"></p>

</form>

<cfdump var="#form#" label="Form values" />

Two things to note about cfmodule:

  1. I originally used “name” instead of “fieldName”, but “name” is an existing attribute of cfmodule which conflicts with the use of “template”.
  2. Do NOT use a trailing slash with cfmodule. This causes it to be called twice.

The final HTML output looks like this:

<form id="myForm" name="myForm" action="" method="post">

<p><input type="text" id="someField" name="someField" /></p>

<select id="mySelect" name="mySelect">
    <option value="">-- Select --</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>

<script type="text/javascript">
    $('#mySelect').val('0');
</script>

<p><input type="submit"></p>

</form>

Conclusion

While the HTML for the select menu’s options in this example was hardcoded, they could have easily come from XML, a list, a query or some other datasource. That data source could then be referenced inside the cfmodule to create the options.

The important thing here is that we were able to populate the jQuery code (client side) using dynamic values rendered via ColdFusion (server side). Once you get used to jQuery’s syntax, you’ll be writing less and less Javascript and getting more done faster.

About the Author
Adrian J. Moreno

Adrian is an enterprise solution architect and full stack developer. Which stack depends on which system is on fire at the time. More information