I'm having some difficulties getting Javascript to execute in a PHP statement if it is possible at all. Below I have the code, if the field 'First' is empty, then the background color of a certain div will be yellow. How can I get this to work properly if it is possible in the first place? Thanks in advance.
if (empty($_POST["First"])) {
echo '<script type="text/javascript">';
echo '$("div").css({"background-color":"yellow"});';
echo '</script>';
}
Death-is-the-real-truth
72.3k10 gold badges59 silver badges106 bronze badges
asked Apr 4, 2017 at 11:26
Lord Goderick
9852 gold badges15 silver badges33 bronze badges
2 Answers 2
check this code. hope it will help you
<div>Content Div</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
//$_POST["First"] = ''; if you want to check this code execute then remove comment then run this code
if (empty($_POST["First"])) {
echo '<script type="text/javascript">';
echo '$("div").css("background-color","yellow");';
echo '</script>';
}
?>
you can also use this code
<div>Content Div</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
//$_POST["First"] = ''; this is for test case if you want to check then remove comment then run this code
if (empty($_POST["First"])) { ?>
<script type="text/javascript">
$("div").css("background-color","yellow");
</script>
<?php } ?>
in this code php tag and javascript tag use separate
answered Apr 4, 2017 at 11:38
Shafiqul Islam
5,6852 gold badges36 silver badges45 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You should try putting script tags inside php tags, like this:
<?php
if (empty($_POST["First"])) { ?>
<script type="text/javascript">
'$("div").css({"background-color":"yellow"});';
</script>
<?php } ?>
Here is an example: https://stackoverflow.com/a/13254287/7808973
Comments
default
<?php if (empty($_POST["First"])) { ?> <script type="text/javascript"> $("div").css({"background-color":"yellow"}); </script> <?php } ?>