Having trouble executing JavaScript within a ColdFusion cfoutput tag

As part of creating a form editor in Coldfusion system, I am keen on leveraging inline script tags for adding Javascript event listeners dynamically. Here is how my code structure looks like:

<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

My goal with this code is to ensure that whenever a textarea element loses focus (onblur event in jquery), I can detect it for each item in my form. However, the current implementation is not achieving the desired result.

Interestingly, when I eliminate the FormElementPK variable and statically reference the "#questionXTextEditor" variable such as "question1TextEditor", the functionality works fine. But due to the need for dynamic generation of questionTextEditor elements, I believe using the FormElementPK variable from Coldfusion is essential.

Answer №1

It appears that there is a missing + sign in the following line:

Wrong:    document.getElementById("##question" + jsFormElementPK "TextEditor");
Right:    document.getElementById("##question" + jsFormElementPK + "TextEditor");

Although this may not directly answer your question, I suggest considering the use of external .js files instead of inline CF code. While it may be faster initially, sending excessive code to the browser with each request can have long-term drawbacks.

In my practice, I often employ some form of

<script>MySite.ThisScreen.MinFiles = 1;</script>

structure in the CF output, while keeping specific functions within the .js file. This approach separates JS from CF and ultimately encourages better Javascript coding habits over time.

I hope the information provided above assists you in resolving your issue.

Answer №2

This solution was discovered during a team meeting on Zoom. It turned out that in order to effectively utilize a JQuery selector (the $() part of the code), it is crucial to reference elements that already exist in the document. The javascript was originally referencing the questionXTextEditor elements located below it, causing issues. By rearranging the script so that it came after the questionXTextEditor elements, the problem was resolved. Check out the screenshot from our virtual meeting where we discussed and solved this issue:

https://i.sstatic.net/qCm8T.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looking for assistance with resizing and repositioning an image within a viewport?

The JSFiddle code can be found at this link - https://jsfiddle.net/pmi2018/smewua0k/211/ Javascript $('#rotate').click(function(e) { updateImage(90, 0) console.log("rotation"); }); $('#zoom-in').click(function() { updateImage(0 ...

'this' while being utilized in a nested function

const EventEmitter = require('events').EventEmitter; const Counter = function (init) { this.increment = function () { init++; this.emit('incremented', init); } } ...

Is it possible to pass additional arguments to setState other than prevState and props?

I'm currently facing an issue with my component that involves calling a function called addOption, which is defined on its parent component. This function takes a parameter 'option' from a form field and concatenates it with an array of opti ...

Anchor checkboxes

I am dealing with a large number of checkboxes that are linked to anchors. Whenever a checkbox is clicked, it navigates to the corresponding anchor on the same page. Is there a more efficient way to implement this? With around 50 checkboxes, my current cod ...

Saving a value in a service using AngularJS

I am facing an issue with passing a variable into a service that needs to be accessed from multiple states within my application. I have created a service and attempted to pass a variable from a controller into the service in order to access it from anothe ...

Ending an $.ajax request when the page is exited

Currently, I have a function set on a timer to retrieve data in the background: (function fetchSubPage() { setTimeout(function() { if (count++ < pagelist.length) { loadSubPage(pagelist[count]); fetchSubPage(); ...

Here's a way to programmatically append the same icon to multiple li elements generated using document.createElement:

I am new to creating a to-do app and need some guidance. When a user enters a task, I successfully create a list item for that task. However, I am unsure how to add a delete icon next to the newly created li element. Can someone please help me out? Below ...

Combining actions in a chain within an NgRx effect for Angular

After successfully working on an effect, I now face the challenge of chaining it with a service called in a subsequent action after updating the state in the initial action through a reducer. Here is the effect code: @Effect() uploadSpecChange$: Observab ...

(MUI Textfield) Error: Unable to access properties of undefined (specifically 'focus')

I have been working with the useRef hook in my Material Ui Textfield and have encountered the error Uncaught TypeError: Cannot read properties of undefined (reading 'focus'). I am unsure how to resolve this issue. Here is my current code snippet: ...

Javascript - When I preview my file, it automatically deletes the input file

My form initially looked like this : <form action="assets/php/test.php" method="post" enctype="multipart/form-data"> <input type="hidden" name="MAX_FILE_SIZE" value="1000000" /> ...

A guide on extracting the text content from an anchor tag by using xPath() with a combination of selenium and Mocha

I have successfully chosen an <a> tag. My goal is to display the text of the anchor tag, but I am facing difficulties. The technologies being used are selenium, mocha, javascript, and phantomJS This is the detailed script: var assert = require(&ap ...

What is the process for removing a Discord user using Node.js?

I've been working on creating a discord bot using node.js, but I'm facing an issue where nothing happens when I try to use a command. The console doesn't log anything except for the bot coming online. const Prefix = '$'; bot.on(&a ...

Steps to retrieve an array from AJAX request and save it to a JavaScript variable

How can I retrieve the 'this.responseText' array from this function and assign it to a variable named 'teacherIDList'? Any suggestions? var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readySt ...

Here are the steps to divide an array of objects into separate objects based on their keys

The data I currently have is formatted like this: [{ "Consumer": [{ "Associated ID": "JSUDB2LXXX / BIC 7503 / US", "Parent Consumer": "7503" }], "Owner": [{ &qu ...

Tips on saving php variable content in HTML "id"

Three variables are used in PHP: message_id, message_title, and message_content. Their content is stored inside HTML 'id' for later use with jQuery. Example: Variables: $id_variable = $rows['id_mensagem']; $message_title_edit = $rows ...

"Object.entries seems to be returning only the initial object in the list

This is my object var obj = { "first_obj": { "a":1, "status": 1 }, "second_obj": { "a":2, "status": 3 } } I'm struggling to loop through this object using foreach and Object.entries, as the latter only returns the first object. How ...

The Ajax form is failing to retrieve the expected PHP data

My login system uses a combination of ajax and php. The form validation is handled through javascript, with the form data then being sent to php for database checks. In the past, this method has worked well for me, but in this instance, it seems 'NOTH ...

Encountering an uncaught error event while using Yeoman

Whenever I try to run Yeoman, I encounter the following error: events.js:72 throw er; // Unhandled 'error' event ^ Error: spawn ENOENT at errnoException (child_process.js:1001:11) at Process.ChildProcess._handle.one ...

I seem to be having trouble with my JavaScript code when attempting to search for items within

I want to implement an onkeyup function for a text input that searches for patient names from column 2 in my table. However, it seems to be not working properly as I don't get any results in return. Below are the snippets of what I have done so far. ...

JavaScript generating HTML code causing malfunctions

I have been attempting to implement the IN Place Editing feature using JQuery. Below is the code snippet editinplace.js $(document).ready(function() { //When div.edit me is clicked, run this function $("div.editme").click(function() { // ...