Have a Wetpaint account? Sign in
Single Quotes, JavaScript, and Event Handlers
The Problem
Embedding event handlers in HTML elements that call JavaScript functions is a very common practice. Unfortunately Microsoft Internet Explorer 6 and 7 have a bug where single quote decimal references ( ' ) will be interpreted as single quote characters ( ' ), when in embedded JavaScript. This can easily cause issues where single quotes are being used as String constants, for example when passing arguments to JavaScript functions.Effectively, the following code:
| <a href="#addPage" onclick="WPCAPI.showAddPageDialog('bob'sPage', 'Bob's Page');"> |
Will be interpreted as the following in Internet Explorer:
| <a href="#addPage" onclick="WPCAPI.showAddPageDialog('bob'sPage', 'Bob's Page');"> |
Clearly, that will cause JavaScript errors at page load time.
The Solution
Make sure any single quotes in JavaScript argument values are either escaped or encoded appropriately. This must happen before the page is rendered, i.e. at compile time via Java, PHP, ASP.NET, etc. There are several options to choose from.| Render an escaped single quote character. | <a href="#addPage" onclick="WPCAPI.showAddPageDialog(">Add a Page</a>'bob\'sPage',); |
| Render a single quote decimal reference, escaping the leading "&". Ordinary HTML/XML escaping will convert single quotes to decimal references. | <a href="#addPage" onclick="WPCAPI.showAddPageDialog(">Add a Page</a> |
| Render a single quote hex reference. URL encoding will convert single quotes to hex references, but an additional JavaScript call will be necessary to decode the string before passing it to the listener. | <a href="#addPage" onclick="WPCAPI.showAddPageDialog(">Add a Page</a> |
|
elaine2 |
Latest page update: made by elaine2
, May 16 2008, 9:36 PM EDT
(about this update
About This Update
No content added or deleted. - complete history) |
|
Keyword tags:
encoding
event handler
IE6 bug
IE7 bug
javascript
onclick
quote
quotes
More Info: links to this page
|
There are no threads for this page.
Be the first to start a new thread.

