3

I'm using PHP to generate a Javascript button that adds in a checkbox and some other HTML.

What is the proper way to escape these characters to include them in an onclick event?

I saw it suggested to convert ' and " to the ascii values, but that doesn't seem to have helped.

$tempOutput = "<a href='temp.txt'>\"Happy\"</a>";
$tempOutput = str_replace("'", "&#39;", $tempOutput);
$tempOutput = str_replace('"', "&quot;", $tempOutput);

just results in this if you echo the string right before use:

<a href=&#39;temp.txt&#39;>&quot;Happy&quot;</a>

and this if you inspect the page element:

<a onclick="
                    var divTag = document.createElement('div');
                    divTag.innerHTML = '&lt;a href='temp.txt'&gt;&quot;Happy&quot;&lt;/a&gt;';
                    document.getElementById('extraDiv').appendChild(divTag) ;
                ">test</a>

I've also tried just appending to the extradiv's innerHTML but no success there either.

3 Answers 3

3

I mostly use PHPs rawurlencode() and Javascript's unescape():

  <?php
    $tempOutput = '<a href="temp.txt">'.htmlentities('"Happy"').'</a>';
  ?>
  <a onclick="
              var divTag = document.createElement('div');
              divTag.innerHTML = unescape('<?php echo rawurlencode($tempOutput);?>');
              document.getElementById('extraDiv').appendChild(divTag) ;
             ">test</a>
  <div id="extraDiv"></div>

This will also avoid errors with other chars, e.g. linebreaks.

1
  • Thanks. This works except for the fact you have to do the htmlentities() first. I essentially cannot do that since the HTML is returned from another source. I don't generate it right before putting it in the onclick. htmlentities() on the whole string doesn't exactly work. Basically everything is okay as long as there's not a double quote in any text in the HTML. Commented Jun 14, 2011 at 12:52
0

Escape like this

$tempOutput = str_replace(array("'",'"'), array("\'",'&quot;'), $tempOutput);
1
  • This worked for the very simple example, but it threw an error again with a more complex example, but it's a start thank you. Commented Jun 14, 2011 at 12:36
0

use html_entity_decode

1
  • I think I want sort of the opposite, but thank you. My input is already in this format. Commented Jun 14, 2011 at 12:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.