Here is a simple code I have problem with:
<label id="label1">
<?php
echo "Text inside label1";
?>
</label>
<script language="JavaScript" type="text/javascript">
var text = document.getElementById("label1").innerHTML;
alert(text); // show what's in variable 'text'
if(text == "Text inside label1")
{
alert("I am inside.");
}
else
{
alert("No.");
}
</script>
The problem is that the first alert is showing “Text inside label1″(as it should do) but the second one is showing “No.”. When I tried to write text right into html (not through php), it worked fine => the second alert showed “I am inside.”. I have no idea what problem is there. Could there be the problem with some differences between string types (php vs. JS) or something like this?
Thanks for any ideas
There is a space at the beginning of the text in the label (all whitespace in HTML is collapsed into one space), but not at the beginning of the string you’re comparing it with.
Your PHP code:
…will get sent to the browser like this (PHP will strip the line break after the
?>for you):…which is just like
(Note the space.)
So this should fix it: