ColdFusion 8: Getting the value of AJAX-ified controls

I ran into a problem last night trying to use JavaScript to read the value of a rich text field. I had assumed I could use the normal syntax I'd use for a form field:

document.forms[0].body.value

or

document.getElementById('body')

But neither of these worked correctly. Turns out the JavaScript API provided in ColdFusion 8 has an API for this: ColdFusion.getElementValue(elementId, formID, attributeName). The formID and attributeName values are optional. Here is a simple example:

<script> function test() { var body = ColdFusion.getElementValue('body'); alert(body); return false; } </script>

<cfform onSubmit="return test()"> <cftextarea richtext="true" name="body" /> <input type="submit"> </cfform>

In case you are curious - the value includes all the HTML from the rich text value as you would probably expect.

The API can also be used on grids and trees. For grids, you have to provide the column name, and for trees you ask for either the node or the path value.

Archived Comments

Comment 1 by ElGuapo posted on 6/19/2007 at 4:49 PM

As a newb I don't really know about AJAX. Could somebody point me in the right direction as to where I can find out more?

Comment 2 by Raymond Camden posted on 6/19/2007 at 5:15 PM

That's kind of a huge question. I'm actually not aware of a a good 'Basic AJAX' site out there. Most frameworks will teach you how to use their frameworks, of course. My personal preference for an AJAX framework is Adobe Spry (you can find it at labs.adobe.com). I find it very simple to learn and use.

Comment 3 by David posted on 6/19/2007 at 6:56 PM

Hi Ray - did you have to use the "ColdFusion" scope because you used the cfform tag?

Comment 4 by Raymond Camden posted on 6/19/2007 at 6:58 PM

The ColdFusion object is included whenever you do AJAXy stuff. It is where the JS API lives.

Comment 5 by todd sharp posted on 6/19/2007 at 7:18 PM

GASP! Ray using a RTE!!!!!!!!!!!

Comment 6 by Raymond Camden posted on 6/19/2007 at 7:24 PM

Don't tell anyone.

FYI, BlogCFC will have an option to enable this out of the box. For those who want it.

Comment 7 by Preston posted on 10/14/2009 at 12:35 AM

Ray,
How would this work if you have two forms on your page, both of which contain the form field body? I understand the format is ColdFusion.getElementValue(elementId [, formId, attributeName]). elementId would be body, formid would be the id of the form, but what do you put in attributeName?

Comment 8 by Raymond Camden posted on 10/15/2009 at 3:16 AM

You would use body for elementid, and then the formid next. So the forms need to have unique IDs.