Turn off double quotes in the onClick JavaScript event handler

A simple block of code below can be served on a static HTML page, but leads to a JavaScript error. How should you avoid the inline double quote in the onClick handler (e.g. xyz)? Note that HTML is generated dynamically by pulling data from a database whose data is fragments of another HTML code that can have one or two quotes. It seems that adding one back slate in front of the double quote character does not 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> 
+51
javascript html javascript-events escaping
Jul 04 '09 at 5:22
source share
5 answers

You tried

&quot; or \x22

instead

 \" 

?

+69
Jul 04 '09 at 5:29
source share

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

+50
Jul 04 '09 at 16:47
source share

Although I agree with the CMS that you do it unobtrusively (via lib, like jquery or dojo), here's what works:

 <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's barfs is not because of JavaScript, but because of the HTML parser. He has no idea about the escaped quotes that he rolls around to search for the final quote and finds it and returns it as an onclick function. This is invalid javascript, although you cannot find the error until JavaScript tries to execute this function.

+5
Jul 04 '09 at 5:41
source share

You can also try two backslashes (\\") to avoid the escape character.

+4
Jul 04 '09 at 5:41
source share

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

Something like that:

 window.onload = function(){ var myLink = document.getElementsById('myLinkId'); myLink.onclick = function(){ parse('#', false, '<a href="xyz'); return false; } } //... <a href="#" id="myLink">Test</a> 
0
Jul 04 '09 at 5:26
source share



All Articles