Nick G
Nick G

Reputation: 1229

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

Upvotes: 1

Views: 6826

Answers (2)

mplungjan
mplungjan

Reputation: 177975

I strongly suggest

code:

formResults += '<a class="openForm" data-text="'+this.displayText + '" id="'+this.ID + '">' + this.displayText + '</a>';

HTMLDisplay:

<a class="openForm" data-text="Example Form (Example Form 1) Application Instructions" id="1108">Example Form (Example Form 1) Application Instructions </a>

jQuery:

$(function() {
  $(".openForm").on("click",function(e) {
    e.preventDefault();
    openForm($(this).data("text"),this.id);
  });
});

Upvotes: 2

tymeJV
tymeJV

Reputation: 104775

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!

Upvotes: 4

Related Questions