0

For some reason some Javascript/Jquery code does not work when placing it inside PHP.

<?php
  if (x > 0) { 
?>    

<script type="text/javascript">   
   alert("Hi!");   
   $("#fault_message_mail").hide();
</script>

<?php
  } else . . .
?>

In case x>0 it is executed only the Alert and not the hide method(I'd like to hide a div declared in some html code).

Why it is not executed? Is it prudent to use jQuery inside PHP?

I've been searching similar questions in Stack overflow, however I cannot find a positive answer.

Thank you

4
  • @ILIAS did you include jquery library ? Commented Sep 2, 2014 at 9:27
  • Do you mean $x>0 instead of x>0? Commented Sep 2, 2014 at 9:29
  • But do you understand WHY you need to change the code? I get the idea that you were under the impression that the javascript would run the moment you see it in your PHP code. Commented Sep 2, 2014 at 9:42
  • so we will need a more information, paste relevant code. Also check console is there any other errors? Commented Sep 2, 2014 at 9:43

3 Answers 3

6

You'll need to attach a handler something like:

$(document).ready(function(){
   ("#fault_message_mail").hide();
});

or

$('#mybutton').click(function(){
   ("#fault_message_mail").hide();
});
Sign up to request clarification or add additional context in comments.

1 Comment

Obviously, the DOM is not fully loaded when manipulating elements of the DOM. @ILIAS
2

You have to inlude jQuery library if you have not included :

<script src="http://code.jquery.com/jquery-1.10.2.js"></script>

and then you have to write you code inside ready function like this :

$(document).ready(function(){
   ("#fault_message_mail").hide();
});

and third thing is that you have written a wrong syntax here :

<?php   
  if (x>0){ ?>
      ^

it should be like this :

<?php   
  if ($x>0){ ?>

Comments

1

maybe the element is not in the dom, try the following

  if (x>0){ ?>

  <script type="text/javascript">
        jQuery(function ($) { // run on document.ready
          alert("Hi!");   
          $("#fault_message_mail").hide();
        });
    </script>
<?php }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.