Search code examples
javascriptjstl

Escaping single quotes in javascript function


I am using fn:escapeXml to escape quotes in a javascript function. This works perfectly with double quotes however it doesn't work with single quotes. Below is the html code:

 <button class = "location" 
   onclick = "locationModelMethod('${fn:escapeXml(listItem.getBaseRate())}','${listItem.getCreateDate()}','${listItem.getId()}','${listItem.getUser().getEmployeeId()}','${listItem.getChecker().getEmployeeId()}','${listItem.getStatus()}', '${listItem.getRemarks()}' ,${listItem.isActive()})" >
${fn:escapeXml(listItem.getBaseRate())}
 </button> 

The error occurs when ${listItem.getBaseRate()} contains a single quote. I am getting an error Uncaught SyntaxError: missing ) after argument list Can anybody help me out with this


Solution

  • Template literals inside function parameters doesn't work. You will need to simply provide parameters.

    For example:

    myFunc(`${myVar}`)
    

    Can be simply used:

    myFunc(myVar)
    

    Also, don't attach inline handler as suggested by CertainPerformance in the comment.

    Example including parameters being passed

    <html>
    
    <body>
      <script>
        // Parameters that get passed into function being fired by onclick
        var myParam = 'param';
    
        function myParameterFunction() {
          return 'functionParam';
        }
    
        function myParameterFunctionWithParams(foo) {
          return foo + 1;
        }
      </script>
    
      <button onclick="myFunction(myParam, myParameterFunction(), myParameterFunctionWithParams(2))">
          Click me!
        </button>
    
      <script>
        function myFunction(a, b, c) {
          console.log('fired', a, b, c)
        }
      </script>
    </body>
    
    </html>