简体   繁体   中英

how to hide a div in php using javascript?

I have a div which needs to be hide with php script. Here is the code that I have written so far...but I am not getting the exact result...

<?php
$s = "2";
if($s == "1")
{
echo "empty fr";
?>
<script type="text/javascript">document.getElementById('#ts').style.display = 'none';</script>
<?php
}
?>
<div id="ts"><label for="terry">Text<input type="checkbox" name="Terry" id="terry" value="1" /></label></div>

Replace

document.getElementById('#ts').style.display = 'none';

by

document.getElementById('ts').style.display = 'none';

There are two problems here.

Firstly, the one suggested by most answerers.

document.getElementById('#ts').style.display = 'none';

You won't need the # here. Remove it.

document.getElementById('ts').style.display = 'none';

But, there is another thing. You are calling this code before the element to hide is loaded, so it won't work. You'll have to either

  • move the <script> after the element to hide

     <div id="ts"><label for="terry">Text<input type="checkbox" name="Terry" id="terry" value="1" /></label></div> <?php $s = "2"; if($s == "1") { echo "empty fr"; ?> <script type="text/javascript">document.getElementById('#ts').style.display = 'none';</script> <?php } ?> 

    If the code you posted is all of the code in that part, this shouldn't cause any side effects as you are not printing any visible content in that part of the PHP.

  • use the onload event.

     <?php $s = "2"; if($s == "1") { echo "empty fr"; ?> <script type="text/javascript"> window.addEventListener("load", function(){ document.getElementById('ts').style.display = 'none'; }); </script> <?php } ?> <div id="ts"><label for="terry">Text<input type="checkbox" name="Terry" id="terry" value="1" /></label></div> 

    This calls the function when the page is loaded.

you don't need # in document.getElementById()

just use it like this

<script type="text/javascript">document.getElementById('ts').style.display = 'none';</script>

You don't need to use the # character when using the pure JavaScript getElementById method call.

So, just change your call to this:

document.getElementById('ts').style.display = 'none';

The hash character is only needed for jQuery, as it uses the Sizzle engine for selectors.

You can learn more about the method call here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM