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:
Your help is greatly appreciated.
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>
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>';