Jump to content

[SOLVED] Javascript not working w/ php script


bwcc

Recommended Posts

Simple javascript:

 

<script language="JavaScript">
function showmenu(e) {
if (e.style.display == "block") e.style.display = "none"; 
else e.style.display = "block";
}
</script>

 

Works perfectly with :

 


<html>
<head>
<!---javascript above inserted here --->
</head>
<body>

<span id="greenText" onclick="showmenu(blackText);" style="color:green; cursor:hand;">Item 2</span><br>
<span id="blackText" style="display:none;">
Subitem 3<br>
Subitem 4<br>
</span>

</body>
</html>

 

but I get a 'style.display is null or not an object' when used in this code :

 


<html>
<head>
<!---javascript above inserted here --->
</head>
<body>

<?
include 'includes/sql_connect.php';
$sql=mssql_query("SELECT * FROM div");	
while ($row = mssql_fetch_array($sql)){
     echo '
          <div class="division" onclick="showmenu('.$row['div_id'].')" title="Click to Edit">'.$row['div'].'</div>
               <div id="'.$row['div_id'].'" style="display:none;">Hi Mom!</div>';
}

?>

</body>
</html>

 

The above sql query returns 4 results currently.  This is what the browser sees:

 

<html>
<head>
<!---javascript above inserted here --->
</head>
<body>

<div class="division" onclick="showmenu(1)" title="Click to Edit">Director</div>
     <div id="1" style="display:none;">Hi Mom!</div>
<div class="division" onclick="showmenu(2)" title="Click to Edit">Administration</div>
     <div id="2" style="display:none;">Hi Mom!</div>
<div class="division" onclick="showmenu(3)" title="Click to Edit">Clinton Water Treatment</div>
     <div id="3" style="display:none;">Hi Mom!</div>
<div class="division" onclick="showmenu(4)" title="Click to Edit">Collection System</div>
     <div id="4" style="display:none;">Hi Mom!</div>


</body>
</html>

 

Any ideas to why this is not working in a 'while' function?

It has to do with the way you are referencing your variables.  When you do showmenu(1), JS assumes you are referring to the integer 1, and not the element.  Instead, you should pass the parameter as a string, such as: showmenu('1'), and your JS showmenu function should be:

<script language="JavaScript">
function showmenu(e) {
        e = document.getElementById(e);
        if (!e) return;
if (e.style.display == "block") e.style.display = "none"; 
else e.style.display = "block";
}
</script>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.