This question already has an answer here:
My function generates a table with $data from a mysqli query requesting sub forum names.
function forum_links($data){
//print_r($data);
echo "<div id = 'sub_forums'>
<table>";
foreach($data as $name){
echo "
<tr>
<td id='sub_forum_image'>
<img src='images/favicon_text.ico' alt='MWGA'>
</td>
<td id='sub_forum_td'>
<a href='forum?forum={$name[0]}'>{$name[0]}</a>
</td>
</tr>";
}
echo "</table></div>";
}
When the text is clicked im checking if the varibale forum is set and if set I want to hide the div 'sub_forums'
<?php
if (isset($_GET['forum'])) {
echo "is set";
?> <script>sub_forum_hide();</script> <?php
}
?>
The error I'm getting
Uncaught TypeError: Cannot read property 'style' of null.
I figure this has something to do with the sequencing of my document because I've use the exact same hide style.display = "none"
in other parts.
function sub_forum_hide(){
document.getElementById("sub_forum").style.display = "none";
}
I've tried moving the sub_forum_hide() to the bottom of my document but I still get the same error. Just for reference the "is set" echo does work when I click the the text.
</div>
From the look of your code.. You dont have any element with ID "sub_forum" which is why it is null. Instead you have a div with ID = "sub_forums"... So your function should actually be
function sub_forum_hide(){
document.getElementById("sub_forums").style.display = "none";
}
Probably a typo on your part.
Next time, try understanding the error first... would save you a lot of trouble and help in debugging.
Change sub_forums to sub_forum.
function forum_links($data){
//print_r($data);
echo "<div id = 'sub_forum'>
<table>";
foreach($data as $name){
echo "
<tr>
<td id='sub_forum_image'>
<img src='images/favicon_text.ico' alt='MWGA'>
</td>
<td id='sub_forum_td'>
<a href='forum?forum={$name[0]}'>{$name[0]}</a>
</td>
</tr>";
}
echo "</table></div>";
}
Looks like your title doesn't really match your problem.
To solve the problem you actually described, you'll need to correct the id of your divs as others pointed out.
If you want to execute some php from javascript, you'll need to use Ajax