To ensure that quotes are correctly handled in a string being passed to a JavaScript function within an `onclick`

I am facing an issue with a cycle in a jspx file that I have. The cycle looks like this:

<c:forEach var="var" items="${dataFile.list.rows}">
  <li>
    <div>
      <a href="#" onClick="myFunct('${var.url}','escape(${var.title}),'escape(${var.descr})');">
        <img width="108" height="66" alt="" src="${var.img}" />
      </a>
    </div>
  </li>
</c:forEach>

The problem arises when the variables ${var.title} or ${var.descr} contain quotes or double quotes. It is difficult to handle these cases as I cannot predict the type of quote that will be present.

I have tried different approaches, such as using a helper JavaScript section before the element, but without knowing the type of quotes in advance, it is challenging to decide whether to use escape("${var.title}") or escape('${var.title}').

If you have any ideas on how to solve this issue, please let me know. Thank you.

Answer №1

It's recommended to handle this task on the server-side rather than the client-side. Trying to do it on the client-side may be too late in the process. Depending on how you intend to use the value, whether it will be included in HTML without line breaks, or as JavaScript code, you have a couple of options available.

<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<a onclick="myFunct('${var.url}','${fn:escapeXml(var.title)}','${fn:escapeXml(var.descr)}');">

You can also create a custom EL function that utilizes Apache Commons Lang's

StringEscapeUtils#escapeJavaScript()
method internally.

<%@taglib prefix="my" uri="http://example.com/functions" %>
...
<a onclick="myFunct('${var.url}','${my:escapeJs(var.title)}','${my:escapeJs(var.descr)}');">

If you need guidance on creating a custom EL function, refer to this answer for an example.

In this case, using fn:escapeXml() should suffice since the value is likely to be part of HTML content.

Answer №2

Avoid the hassle of creating your own EL function by utilizing apache-commons directly within your custom .tld file:

<function>
    <name>escapeJavaScript</name>
    <function-class>org.apache.commons.lang.StringEscapeUtils</function-class>
    <function-signature>java.lang.String escapeJavaScript(java.lang.String)</function-signature>
</function>

Answer №3

My recommendation is to perform encoding on the server side by visiting

Alternatively, you can store the data in a hidden element

<span id="url" style="display:none">${var.URL}</span>
<span id="title" style="display:none">${var.title}</span>
<span id="desc" style="display:none">${var.descr}</span>

and use

onClick="return myFunct(['url','title','desc'])">...</a>

function myFunct(parms) {
  var url   = parms[0]?document.getElementById(parms[0]).innerHTML:"No url";
  var title = parms[1]?document.getElementById(parms[1]).innerHTML:"No title";
  var descr = parms[2]?document.getElementById(parms[2]).innerHTML:"No description";
  return false;
}

Answer №4

In order to successfully call the function myFunct, you must provide a valid JavaScript String literal as an argument. The escape function in JavaScript also requires a valid String input. Therefore, it is necessary to convert your Java String into a proper JavaScript literal first. One way to achieve this is by utilizing apache commons-lang library's

StringEscapeUtils.escapeECMAScript
method for escaping. You can even turn this process into a custom Expression Language (EL) function and incorporate it like so:

onClick="myFunct('${myFn:escapeJs(var.url)}','${myFn:escapeJs(var.title)}, '${myFn:escapeJs(var.descr)}');"

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

Guide on appending a file to a formData object in vue.js

Having trouble adding the file from the input to the formData object. Even after trying multiple solutions, the object appears to be empty when I log it. Can't seem to figure out what's wrong. File Input: <input class="btn btn-sm btn-rounded ...

Using jQuery to toggle CSS properties

I'm having trouble switching between a CSS column layout and a normal layout for a div element with the ID 'article'. The jQuery script I wrote doesn't seem to work properly, as the entire thing disappears. Can anyone advise me on how t ...

Discover the process of executing two functions simultaneously by interacting with a VRbutton through React360

As a newcomer to React, I am still learning the ropes and facing a challenge with using two functions simultaneously with Vrbutton (or any button) on onClick event. I have attempted various methods (referenced in my commented out code below) to make multi ...

Struggling to capture an error generated by Sequelize within a universal Middleware block

In a test project, I have successfully implemented CLS transaction control in Sequelize using 'cls-hooked'. The transactions work seamlessly both in the command line and with Express. They are injected and managed automatically, rolling back on a ...

The order of items in MongoDB can be maintained when using the $in operator by integrating Async

It's common knowledge that using {$in: {_id: []}} in MongoDB doesn't maintain order. To address this issue, I am considering utilizing Async.js. Let's consider an example: const ids = [3,1,2]; // Initial ids retrieved from aggregation con ...

The mute feature in Discord.js along with setting up a muterole seems to be malfunctioning and encountering errors

Currently, I am working on implementing a mute command feature. The main goal is to have the bot automatically create a role called Muted if it doesn't already exist, and then overwrite the permissions for every channel to prevent users with that role ...

Battle between Comet and Ajax polling

I'm looking to develop a chat similar to Facebook's chat feature. Using Comet would require more memory to maintain the connection. There seems to be a latency issue when using Ajax polling if requests are sent every 3-4 seconds. Considering t ...

Incorporate the previous page's location path into the next page using Props in Gatsby Link

My website has multiple pages with paginated lists of blog posts, each post generated from markdown using createPage(). Each page in the /posts directory displays 3 post previews and subsequent pages are numbered (e.g. /posts/2). I am trying to pass the p ...

Why does Vue 3 refuse to refresh an <img> element, while it successfully refreshes all other components within the same component?

In my current Vue project, I have set up multiple link cards (<a class='card'></a>) inside a "deck" container (<div class='deck'></div>). The implementation for these elements is relatively straightforward: <s ...

Utilizing ExpressJS: importing Multer module in a separate file

After following the instructions in the GitHub readme file for multer, I encountered a dilemma. The readme suggested calling multer in middleware as shown below: app.js var multer = require('multer') app.post('/upload', upload.single( ...

Combining PHP JQuery Dialog with Datatables results in a sleek design loss

Recently, I encountered an issue with my code. I have a file called incident_view.php which pulls data from the database and displays it using Datatables. Everything was working fine until I tried to open this page in a JQuery dialog on another page called ...

While attempting an AJAX request with jQuery, I encountered the following error message: "Error: ER_SP_UNDECLARED_VAR: Undeclared variable: NaN"

I encountered an issue that says: ` throw err; // Rethrow non-MySQL errors ^ Error: ER_SP_UNDECLARED_VAR: Undeclared variable: NaN ` while attempting a jQuery AJAX get request, and I'm unsure of the cause. My backend is built using node.js a ...

The created function in VueJS may sometimes result in an undefined outcome

I recently started a project with VueJs where I encountered an issue while making a GET request using the Axios library. The data was returned as expected, but I faced difficulties calling the loadUsers function inside mounted. Here is my code snippet: ex ...

What is the process for transferring npm package files to my local project?

Despite my efforts to find the answer, I couldn't locate it and so here I am asking again. What I'm looking for: I need to move a file from node_modules to my project in order to work on it. First attempt: I moved the file I wanted to edit An ...

What's going on with the background color? It doesn't seem

I have incorporated Bootstrap into my html code and I am attempting to modify the background color of a div when the screen resolution changes from large to medium or small. Even though I have added a class, the change does not reflect when adjusting the ...

Swap out a particular component during the testing phase

Currently, I am running tests on my React-Redux application using Jest. Within my API calls, I have integrated a fetch module called cross-fetch. However, I am looking to substitute this with fetch-mock. Take a look at my directory structure: Action.js i ...

What is the best way to determine the total number of rows in a JSON file?

Here is the JSON data I have: [0:{name:"jason",height:"150cm"}, 1:{name:"henry",height:"178cm"}] In my function, I am attempting to create a for loop like this: function DrawTable(output) { var ...

What is the best way to align a <div> element below another without being on the same line?

I'm currently working on developing a snake game. My focus right now is figuring out how to make the body parts of the snake follow the head and be positioned after it. <!--Player--> <div class="snake"></div> So here we have the sn ...

Encountering the React.Children.only error while trying to use the <Link> component in Next.js

I'm encountering an issue with the code below: Error: React.Children.only expected to receive a single React element child. While trying to troubleshoot, I noticed that it only allows me to have one header under the link. <div className="co ...

Is there a way to pass a c struct pointer into javascript using ffi?

I need help passing a pointer to a struct to a method in nodejs using ffi. I am encountering an error where the type of the JavaScript struct I created cannot be determined. How can I resolve this issue? Previously, I was able to successfully implement si ...