When outputting values from a database to an HTML page, it's crucial to handle certain characters, such as quotes, correctly to prevent unexpected behavior.
Consider the example where a string retrieved from a database needs to be used as a parameter in an onclick HTML attribute:
<a href="" onclick="DoEdit('DESCRIPTION');">Click Me</a>
If DESCRIPTION contains a space and quote, such as:
Prelim Assess "Mini" Report
Firefox prematurely truncates the onclick attribute after the space in "Assess" due to the double quote after "Assess".
To resolve this issue, it's necessary to "escape" the troublesome quotes. While using the JavaScript escape character is insufficient in this HTML context, a different approach is required.
The solution involves replacing the double quote character with its corresponding XML entity representation, ". This will ensure that the double quote is interpreted as a string delimiter within the HTML attribute:
<a href="#" onclick="DoEdit('Preliminary Assessment &quot;Mini&quot;'); return false;">edit</a>
By escaping the double quotes in the string, the onclick attribute now operates as intended.
The above is the detailed content of How to Escape Quotes in JavaScript for HTML Attributes?. For more information, please follow other related articles on the PHP Chinese website!