user2106416
user2106416

Reputation: 37

Javascript inside php not working

I have a script inside php that will change the display of a div when a checkbox is checked, the checkbox location is different from the place where the script is located.

the snippets of the code is shown below

        if($_POST['test'] == 1)
        {
            echo "<script> document.getElementById('seoTerm').style.display='block';</script>";}

I placed the above code in the head of the current page. When the $_POST['test'] is 1, the display of the div with id seoTerm is still none, instead of block.

What's the problem here ?

Upvotes: 0

Views: 138

Answers (4)

Robert
Robert

Reputation: 20286

There are 2 solutions you need either use document.ready event or you can echo this code after the element is displayed.

If you do it before the element may not exsits when JavaScript tries to bind an event to it.

echo "<script>window.onload = function(){ document.getElementById('seoTerm').style.display='block'};</script>"

Upvotes: 0

Johan Bouveng
Johan Bouveng

Reputation: 565

It might fire to early in order to manipulate the DOM.

Try:

<script>
window.onload = function(){
    document.getElementById('seoTerm').style.display='block';
};
</script>

Upvotes: 6

som
som

Reputation: 4656

Use

echo "<script>document.getElementById('seoTerm').style.display='block';</script>";

instead of

echo "<script?> document.getElementById('seoTerm').style.display='block';</script>";

Upvotes: 0

Vishnu Sureshkumar
Vishnu Sureshkumar

Reputation: 2316

There is a mistake in the script tag

change to <script> and not <script?>

Upvotes: 1

Related Questions