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
3 Answers 3
You'll need to attach a handler something like:
$(document).ready(function(){
("#fault_message_mail").hide();
});
or
$('#mybutton').click(function(){
("#fault_message_mail").hide();
});
1 Comment
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
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 }
$x>0instead ofx>0?