ColdFusion.getElementValue and $CF()

Sep 13, 2007

I first started doing Ajax programming using the Prototype framework.  As I learn the new CF8 Ajax features, I find myself looking for simple ways to replicate some of the functionality that is in prototype.  With prototype, you use $F('element') to return the value of a form field.  There is a similar method for CF8, but it needs a little tweak... 

The function that returns the value of a form element in ColdFusion 8's Ajax implementation is the following:

 ColdFusion.getElementValue(id);

It's really handy because it will return a form field value for any type of form field - even select boxes and radio button. 

However, that's a lot of typing if you are using many form values in your JavaScript/Ajax code.  There is a super easy way to reduce this.  Make your own shorter function that just calls this.

 For example,

function $CF(element) {
        return ColdFusion.getElementValue(element);
        }

 Here is an oversimplified example:

 <cfajaximport />
<cfform action="" method="post">
<cfinput type="text" name="testelement" VALUE="test" />
</cfform>
<script>
    function $CF(element) {
        return ColdFusion.getElementValue(element);
        }
    window.alert($CF('testelement'));    
</script>

You could put the $CF function in a JS file that is used throughout your application.  But remember, you can only use ColdFusion.getElementValue() on pages that invoke the Ajax libraries.  In the example above, that's why I placed a <cfajaximport /> tag in there.  This example doesn't use Ajax, and including the libraries is really a waste of resources in this circumstance.  Save this trick for your true Ajax apps.  

More about ColdFusion.getElemenValue() from Adobe

 

Comments

Michael Skinner

Michael Skinner wrote on 07/07/08 12:41 PM

Ok, but how do you do a ColdFusion.SETElementValue(element);"
Michael Skinner

Michael Skinner wrote on 07/07/08 12:42 PM

Ok, but how do you do a ColdFusion.SETElementValue(element);"
Mike Sprague

Mike Sprague wrote on 07/07/08 2:08 PM

There is no built-in CF way to do this - as far as I know. However, you can use this function...

function setElementValue(formElement, value)
{
   switch(formElement.type)
   {
      case 'undefined': return;
      case 'radio': formElement.checked = value; break;
      case 'checkbox': formElement.checked = value; break;
      case 'select-one': formElement.selectedIndex = value; break;

      case 'select-multiple':
         for(var x=0; x < formElement.length; x++)
            formElement[x].selected = value[x];
         break;

      default: formElement.value = value; break;
   }
}

Write your comment



(it will not be displayed)





About Michael Sprague

Mike is a Web developer and manager from Central New York, specializing in ColdFusion, CSS, JavaScript, and Ajax development. More ...

Categories

Monthly Archives

Favorite Bloggers

Web Resources