tb1
tb1

Reputation: 1386

Passing quotes to an onclick event within an html element within a Javascript function

This seems to be one step more complicated than similar posts I've seen:
I created the following line within a js function:

content.push("<input type='button' value='Use This Location' onclick='alert(" + result.location.y + "," + result.location.x + ")'/>");

The result is a button with the following: onclick="alert(40.7445068,-73.9834671)"

but I want the result to be: onclick="alert('40.7445068,-73.9834671')"

or.. you know.. just.. however it would take to make the alert show the text, not just the first number.

How can I reformat the quotes within the original block to make that happen?

Upvotes: 3

Views: 9720

Answers (3)

Thanks so much folks! Your input (no put intended) led to a workable solution: content.push('<input type="button" value="Use This Location" onclick="alert(&#39;'+ result.location.y + "," + result.location.x + '&#39;)" />');

Since it's Javascript within HTML within Javascript, I passed the push method as single quotes instead of the original double ones, then I was able to make the html element double quotes and the onclick single. Then I had to use &#39; instead of &#34 so I could get a special single quote inserted within the HTML.

Again, thanks very much. All the comments were key in solving / I am grateful!

Upvotes: 0

TheZ
TheZ

Reputation: 3732

content.push("<input type='button' value='Use This Location' onclick='alert(\"" +
result.location.y + ',' + result.location.x + "\")'/>");

EDIT: Fixed up the code some.

Upvotes: 1

Christopher Gillis
Christopher Gillis

Reputation: 197

You should just be able to add escaped single quotes (e.g. \')

so change

onclick='alert(" + result.location.y + "," + result.location.x + ")'

to

onclick='alert(\'" + result.location.y + "," + result.location.x + "\')'

edit: formatting issues

Upvotes: 0

Related Questions