chris342423
chris342423

Reputation: 451

JavaScript: Single quote ' causes error

I have a string with a ' inside it:

<a href="#" onclick="if (confirm('... &#039; ...')) { document.exampleFormName.submit(); }">example link text</a>

Unfortunately this does not seem to work. Firebug says "SyntaxError: missing ) after argument list" and you can see that the HTML entity has already been replaced by '.

What can I do to avoid this problem?

Upvotes: 1

Views: 2500

Answers (3)

M3ghana
M3ghana

Reputation: 1281

Try this

<a href='#' onclick='if (confirm("... &#039; ...")) 
{ 
  document.exampleFormName.submit(); 
}'> example link text
</a>

Because "#039" stands for single quote so ('...'...') in your previous code would fail because of this reason

Upvotes: 1

Kokizzu
Kokizzu

Reputation: 26908

It's not beautiful to write like that XD

<a href="#" onclick="if (confirm('... &#039; ...')) { document.exampleFormName.submit(); }">example link text</a>

It's better to use a function

<script>
  function foo() {
    if (confirm("...' ...")) { document.exampleFormName.submit(); }
    return false; // disable the link
  }
</script>
<a href='#' onclick='return foo()'>example link text</a>

but maybe that just me..

Upvotes: 5

Tschallacka
Tschallacka

Reputation: 28742

You should escape quotes. not use html entities. In a '' string you use \' to escape single quotes.

Read more about escape characters: https://mathiasbynens.be/notes/javascript-escapes

    
    <a href="#" onclick="if (confirm('... \' ...')) { document.exampleFormName.submit(); }">example link text</a>

Upvotes: 3

Related Questions