March 18, 2006

innerHTML with ColdFusion

Filed under: ColdFusion, JavaScript — Phillip Holmes @ 3:50 pm

I hear lots of hype about AJAX these days but actually this technology is nothing new. While the use AJAX is a great tool, AJAX and the type of functionality it makes available has been around for many years. AJAX has simply standardized the model. Writing dynamic data to the DOM is really no big mystery and does not require anything more than old fashioned JavaScript and your favorite server side language. My advice about AJAX is to carefully consider what your application needs instead of running in and implementing it because it is the new buzzword or just because you can.

Here is an example of data that comes from a couple CF arrays and is then dynamically inserted into a JavaScript array. This data is then passed to a layer which utilizes the innerHTML tag to display it.

CODE:

  1. <cfscript>
  2.      arProdIDs = arraynew(1);
  3.      arProdIDs[1] = 240;
  4.      arProdIDs[2] = 256;
  5.      arProdIDs[3] = 257;
  6.      arPrice = arraynew(1);
  7.      arPrice[1] = 9.99;
  8.      arPrice[2] = 10.99;
  9.      arPrice[3] = 11.99;
  10.     intCount = arrayLen(arProdIDs);
  11.     intDiscount = 100;
  12. </cfscript>
  13. <script>
  14.      var products = new Array();
  15. </script>
  16. <cfscript>
  17.       for(i=1; i lte intCount;i=i+1) {
  18.            if(i EQ 1) {
  19.                 writeOutput('<script>');
  20.            }
  21.            writeOutput('products[#arProdIDs[i]#] = #arPrice[i]#;');
  22.            if(i EQ intCount) {
  23.                 writeOuput('</script>');
  24.            }
  25.       }
  26. </cfscript>
  27. <script>
  28.     function changeText(obj_input) {
  29.          intDiscount = #intDiscount#;
  30.          for(it in products) {
  31.               if(obj_input==it) {
  32.                    document.getElementById('dynaText').innerHTML =  intDiscount - products[it];
  33.                }
  34.           }
  35.      }
  36. </script>
  37. <div id="dynaText"></div>
  38. <form action="thispage.cfm" method="post" name="myform">
  39.      <cfloop from="1" to="#IntCount#" index="i">
  40.           <cfoutput>
  41.                <input type="radio" name="prodid" value="#arProdIDs[i]#" onclick="changeText(this.value)"/> #arProdIDs[i]#<br />
  42.           </cfoutput>
  43.      </cfloop>
  44.      <br />
  45.      <input type="submit"/>
  46. </form>

With ColdFusion 7, the export of dynamic data from ColdFusion to JavaScript has been made much easier with the addition of the toScript() function. I'll be posting more about toScript() and also about how to dynamically populate select menus without refreshing the page soon, so stay tuned!

The Holmes Blog