Jake Jake - 7 months ago 8
Javascript Question

jQuery not seeing string in span that's displayed with php echo

My php page looks something like this (with jQuery loaded above the script). It works correctly (the css for #desc-* changes from display:none to display:inline) when the text within span id="description" is normal text, but when using php echo function (it's retrieving the string value for $itemdesc from the URL; the value can either be "Product A" or "Product B") to display the string, the code doesn't work. I thought the ready function would let the PHP / DOM load and it would work, but nope.

Edit: I removed the php short tag but that didn't help. (The echo function was working with or without the short tag).

Edit #2: I'm now using @Alex Andrei 's js code. But the issue seems to be due to using _GET (my knowledge here is limited). As a test, I replaced

<?php $itemdesc=$_GET["itemdesc"]; >
with
<?php $itemdesc = 'Product A';>
and then echo'd it, and the javascript worked.

Edit 3: Solved. the strings weren't matching 100% because of white space characters.

<?php $itemdesc=$_GET["itemdesc"]; ?> //can be "Product A" or "Product B"

<html>

<style>
#desc-a, #desc-b {display: none;}
</style>

You purchased: <span id="description"><?php echo $itemdesc ?></span> and
<span id="desc-a">you'll get it in 1 day.</span>
<span id="desc-b">you'll get it in 5 days.</span>

<script>
$(document).ready(function () {
debugger;
var c = document.getElementById("description").innerHTML;

if (document.getElementById("description").innerHTML == "Product A") {
document.getElementById("desc-a").style.display = "inline";

if (document.getElementById("description").innerHTML == "Product B") {
document.getElementById("desc-b").style.display = "inline";
}
});
</script>

Answer

You don't need jQuery for this

See the below example

<?php

$itemdesc = trim($_GET["itemdesc"]);

?>

<script type="text/javascript">

var desc = document.getElementById("description");

switch(true){

  case desc.innerHTML == 'Product A':
    document.getElementById("desc-a").style.display = "inline";
    break;

  case desc.innerHTML == 'Product B':
    document.getElementById("desc-b").style.display = "inline";
    break;

}
</script>

Also your if blocks are not opened/closed properly.

UPDATE:
I added a trim around the GET to do away with any leading or trailing whitespace such as newlines or spaces.

You should definitely consider the approach @SurrealDreams proposed in his answer since it takes away a number of security issues.

Comments