Jake Jake - 1 year ago 53
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"]; >
<?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"


#desc-a, #desc-b {display: none;}

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>

$(document).ready(function () {
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";

Answer Source

You don't need jQuery for this

See the below example


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


<script type="text/javascript">

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


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

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


Also your if blocks are not opened/closed properly.

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download