This should be simple enough, alas it's giving me issues:
I have a PHP page that gives me up to three different iterations of td
contents. The first is shown with display: table-cell
, and the others are hidden with display: none
.
echo '<td style="display: table-cell" class="gameLineCell" id="'.$playerLine.'" colspan="3">';
&
echo '<td style="display: none" class="gameLineCell" id="'.$playerLine.'" colspan="3">';
I then have a link corresponding to each td
option -- clicking it is supposed to run a function loadLine
into which I pass a string that corresponds to the td
ID. ID strings akin to 'EV-F1' -- five characters, a number, a hyphen.
echo "<a onclick='loadLine(".$playerLine.")' href='javascript:void(0)'>".$playerLine."</a>";
The script hides all td
s of the class gameLineCell
, and displays the one whose link was clicked.
<script>
function loadLine(line) {
var lines = document.getElementsByClassName('gameLineCell');
for (var i = 0; i < lines.length; i++) {
lines[i].style.display = 'none';
}
document.getElementById(line).style.display = 'table-cell';
}
</script>
When I view the source of my PHP page everything renders properly -- my links show the proper strings in the loadLine
brackets, each of my td
s is present, the first showing and the others hidden -- however my links do not work. I've tried removing the getElementsByClassName
sequence, running only the getElementById
, though to no avail. Nothing happens.
Any ideas?
Much obliged to any help,
Andrew
EDIT: Source of the error? Javascript is cutting my strings! EV-F1 becomes EV. Looking into the whys and how fix now.
There are a few issues here related to proper escaping and enclosure of strings; I personally use printf()
to print HTML, this is what it would look like:
printf('<td style="display: table-cell" class="gameLineCell" id="%s" colspan="3">',
htmlspecialchars($playerLine, ENT_QUOTES, 'UTF-8');
);
This piece of code in particular is tricky:
echo "<a onclick='loadLine(".$playerLine.")' href='javascript:void(0)'>".$playerLine."</a>";
The problem is that $playerLine
doesn't contain JavaScript string enclosures and so it would attempt to resolve EV-F1
into EV - F1
(i.e., the subtraction of EV
and F1
). To fix that, you need to encode the variable using JSON and then apply HTML escaping:
printf('<a onclick="loadLine(%s)" href="javascript:void(0)">%s</a>',
htmlspecialchars(json_encode($playerLine), ENT_QUOTES, 'UTF-8'),
htmlspecialchars($playerLine), ENT_QUOTES, 'UTF-8')
);
You have a typo on the code you show. There is an extra )
here
for (var i = 0; i < lines.length); i++)
it should be
for (var i = 0; i < lines.length; i++)