photo_tom
photo_tom

Reputation: 7342

Passing double quotes in JavaScript function parameter

I'm have trouble with the following html

<span onClick="alert('hi&#34 more stuff')">Works</span><br/>
<span onClick='alert("Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean.")'>Works long text</span>
<br />
<span onClick='alert("Far far &#34 away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean.")'> Doesn't work long text</span>

My problem is that in the third onclick handler, I'm getting an unterminated string error in the browser. In the real program, the parameter strings are being generated client side, so all encoding has to happen there.

In the example that does work, I've tried both &#34; and &quot; and works in the last example. But they do work in the first example

There is a working sample at http://jsfiddle.net/photo_tom/9d43U/1/

Upvotes: 1

Views: 11712

Answers (3)

VisioN
VisioN

Reputation: 145458

Just escape it with a backslash \".

Upvotes: 3

pauldcomanici
pauldcomanici

Reputation: 601

first you should write html like:

attribute="property"

so if you write:

onclick="alert('what you want here with encoded content it will work')"

see your updated fiddler http://jsfiddle.net/darkyndy/9d43U/5/

Upvotes: -3

Quentin
Quentin

Reputation: 944441

To use a " in a JavaScript " delimited string, use \".

To use a " in an HTML " delimited attribute value, use &quot;.

Combine them if needed: \&quot;


Alternatively, stop using intrinsic event attributes, write unobtrusive JavaScript and bind your event handlers programatically.

Upvotes: 10

Related Questions