Search code examples
javascriptcoldfusioncoldbox

Running javascript unsuccessfully inside of Coldfusion cfoutput tag


I am making a form editor in Coldfusion and I want to use inline script tags to dynamically add Javascript event listeners. The structure of my code looks a bit like the following:

<cfoutput>
...
     <cfloop>
          <cfset FormElementPK = rc.formElements.getRow(i)["FormElementsPK"]>
          <script>
               //Create a listener for the question text editor to check for errors on blur
               var #toScript(FormElementPK, "jsFormElementPK")#;
               var inputField = document.getElementById("##question" + jsFormElementPK + "TextEditor");
               $("##question" + jsFormElementPK + "TextEditor").on('blur', function(e) {
                                alert("I am a test message!");
                                checkQuestionTextForErrors(inputField.id);
                            });         
          </script>
          ...
     </cfloop>
...
</cfoutput>

EDITED: Added correct concatenation by credit of Will Belden

The intended effect of this code is for each element in my form, I want to be able to detect when a textarea element loses focus (onblur event in jquery). This code does not work, however.

It does work when I remove the use of the FormElementPK variable and just reference the "#questionXTextEditor" variable in a hardcoded manner like "#question1TextEditor". However, I need to dynamically generate my list of questionTextEditor elements, so I feel like I need to reference the FormElementPK variable from coldfusion.


Solution

  • This question was answered within a slack channel. Effectively, if you want to use a JQuery selector ( the $() part of the code), you need to reference elements that already exist in the document. The questionXTextEditor elements referenced in the javascript were BELOW the script that was referencing them, so I moved the script below the questionXTextEditor elements and it started to work. Here's the slack convo that solved the problem:

    enter image description here