0

I've been trying to figure this thing out and I don't know what I'm doing wrong or maybe I'm missing something.

I'm trying to pass a string which contains double quotes that I retrieved from my database to be displayed in a textarea.

Situation sample looks like this:

<?php
   $content = '<div align="center"><b>This is a sample content.</b></div>';
   echo '<textarea id="myTextArea"></textarea>';
   echo '<button onclick="myFunction('.$content.')">Click me</button>';
?>

<script>
  function myFunction(content){
    document.getElementById("myTextArea").innerHTML = content;
  }
</script>

Expected results should be that myTextArea should contain the text, but the result shows:

Output

Your help is greatly appreciated.

2
  • 3
    try this $content = '<div align="center"><b>This is a sample content.</b></div>'; Commented Dec 5, 2017 at 8:23
  • that was a typo on my part but output stays the same Commented Dec 5, 2017 at 8:38

2 Answers 2

1

You should quote your output using htmlspecialchars(), such that it reads:

<?php
   $content = "<div align=\"center\"><b>This is a sample content.</b></div>";
   echo '<textarea id="myTextArea"></textarea>';
   echo '<button onclick="myFunction(\''.htmlspecialchars($content).'\')">Click me</button>';
?>

<script>
  function myFunction(content){
    document.getElementById("myTextArea").innerHTML = content;
  }
</script>
Sign up to request clarification or add additional context in comments.

Comments

0

You need to escape your quotes inside the string:

   $content = "<div align=\"center\"><b>This is a sample content.</b></div>";

You could also use apostrophes in this case, like

   $content = "<div align='center'><b>This is a sample content.</b></div>";

or

   $content = '<div align="center"><b>This is a sample content.</b></div>';

EDIT:

Also, make sure you use content as a string:

echo '<button onclick="myFunction(\''.$content.'\')">Click me</button>';

Comments

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.