user133046
user133046

Reputation: 703

Escaping double quotes in JavaScript onClick event handler

The simple code block below can be served up in a static HTML page but results in a JavaScript error. How should you escape the embedded double quote in the onClick handler (i.e. "xyz)? Note that the HTML is generated dynamically by pulling data from a database, the data of which is snippets of other HTML code that could have either single or double quotes. It seems that adding a single backslash ahead of the double quote character doesn't do the trick.

<script type="text/javascript">
    function parse(a, b, c) {
        alert(c);
    }
</script>

<a href="#x" onclick="parse('#', false, '<a href=\"xyz'); return false">Test</a>

Upvotes: 70

Views: 112771

Answers (5)

Aseem Kishore
Aseem Kishore

Reputation: 10898

It needs to be HTML-escaped, not Javascript-escaped. Change \" to &quot;

Upvotes: 65

Landon Kuhn
Landon Kuhn

Reputation: 78511

Did you try

&quot; or \x22

instead of

\"

?

Upvotes: 105

Mark A. Nicolosi
Mark A. Nicolosi

Reputation: 85681

You may also want to try two backslashes (\\") to escape the escape character.

Upvotes: 5

seth
seth

Reputation: 37297

While I agree with CMS about doing this in an unobtrusive manner (via a lib like jquery or dojo), here's what also work:

<script type="text/javascript">
function parse(a, b, c) {
    alert(c);
  }

</script>

<a href="#x" onclick="parse('#', false, 'xyc&quot;foo');return false;">Test</a>

The reason it barfs is not because of JavaScript, it's because of the HTML parser. It has no concept of escaped quotes to it trundles along looking for the end quote and finds it and returns that as the onclick function. This is invalid javascript though so you don't find about the error until JavaScript tries to execute the function..

Upvotes: 8

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 828070

I think that the best approach is to assign the onclick handler unobtrusively.

Something like this:

window.onload = function(){
    var myLink = document.getElementsById('myLinkId');
    myLink.onclick = function(){ 
        parse('#', false, '<a href="xyz');
        return false;
    }
}

//...


<a href="#" id="myLink">Test</a>

Upvotes: 1

Related Questions