Joyeeta Sinharay
Joyeeta Sinharay

Reputation: 185

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>

Upvotes: 0

Views: 77

Answers (4)

Vincent
Vincent

Reputation: 175

Replace

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

by

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

Upvotes: 2

PurkkaKoodari
PurkkaKoodari

Reputation: 6809

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.

Upvotes: 2

Mike Rock&#233;tt
Mike Rock&#233;tt

Reputation: 9007

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.

Upvotes: -1

PravinS
PravinS

Reputation: 2584

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

just use it like this

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

Upvotes: 0

Related Questions