Search code examples
javascriptjquerysyntax-errorparentheses

Parentheses in string of javascript function call


I have a loop that creates links with a javascript function call in the onClick events and uses the text returned from a database as one of the parameters. My issues I am having is that sometimes this text being returned has parenthesis in them which is causing a syntax error in my code. Example:

code:
formResults += "<a onclick='openForm(" + this.displayText + "," + this.ID + ");'>" + this.displayText + "</a>";

HTMLDisplay:
<a onclick="openForm(Example Form (Example Form 1) Application Instructions ,1108);">Example Form (Example Form 1) Application Instructions </a>

as you can see the name of the form contains a set of parenthesis. Is there anyway I can include these? The reason I need to is because the function points to another system that uses the ID and displayText in order to render the proper form. thank you


Solution

  • The parenthesis aren't the problem, it's the lack of quotes inside the function.

    formResults += "<a onclick='openForm(\'" + this.displayText + "," + this.ID + "\');'>" + this.displayText + "</a>";
    

    This below snippet (from yours)

    `openForm(Example Form...`)
    

    Will throw an error because it's looking for variables Example and so on, quote that string!