Tom Tucker
Tom Tucker

Reputation: 11916

Escaping Double Quotes in HTML Event Handlers

How do I escape double quotes in an event handler in HTML?

For example, how do I properly escape the bar, which is a string literal, in the following code?

<button onclick="foo("bar")")>Click Me</button>

I can't use single quotes for the attribute value since I'm using XHTML. I could use single quotes for string literals, but I'd like to be consistent.

Upvotes: 1

Views: 1598

Answers (2)

Ryan Li
Ryan Li

Reputation: 9340

<button onclick="foo(&quot;bar&quot;);">Click Me</button>

And, you can mix them indeed in XHTML, try this in the W3 validator:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>foo</title>
</head>
<body>
<div onclick='bar("foo");'></div>
</body>
</html>

There are some tutorials which said single quotes are not valid, but they are incorrect.

Upvotes: 1

Jason McCreary
Jason McCreary

Reputation: 73031

XHTML prefers double quotes around the attributes. But you can still use single quotes inside the value. The follow for example is XHTML 1.0 Strict

<button onclick="foo('bar')">Click Me</button>

I would suggest looking into progressive enhancement and moving away from the behavioral attributes.

Upvotes: 1

Related Questions